Daily Coding Challenge #110

wingkwong profile image Wing-Kam ・2 min read


This is a series of Daily Coding Challenge. Each day I show a few solutions written in C++. The questions are from coding practice/contest sites such as HackerRank, LeetCode, Codeforces, Atcoder and etc.

Largest Time for Given Digits

Given an array of 4 digits, return the largest 24 hour time that can be made.

The smallest 24 hour time is 00:00, and the largest is 23:59.  Starting from 00:00, a time is larger if more time has elapsed since midnight.

Return the answer as a string of length 5.  If no valid time can be made, return an empty string.

Example 1:

Input: [1,2,3,4]
Output: "23:41"
Example 2:

Input: [5,5,5,5]
Output: ""


A.length == 4
0 <= A[i] <= 9

class Solution {
    string largestTimeFromDigits(vector<int>& A) {
        sort(A.rbegin(), A.rend());
        do {
                return to_string(A[0])+to_string(A[1])+":"+to_string(A[2])+to_string(A[3]);
        } while(prev_permutation(A.begin(), A.end()));
        return "";

Binary Search

Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1


You may assume that all elements in nums are unique.
n will be in the range [1, 10000].
The value of each element in nums will be in the range [-9999, 9999].


class Solution {
    int search(vector<int>& nums, int target) {
        int n=(int) nums.size(), l=-1, r=n;
            int m=l+(r-l)/2;
            if(target<=nums[m]) r=m;
            else l=m;
        return r<n&&nums[r]==target?r:-1;

There are other programming solutions in the following repositories below. Star and watch for timely updates!

GitHub logo wingkwong / competitive-programming

🌟 My CP Journey - This repository contains CP solutions (mostly written in C++) from different OJs and contest sites 🌟

Posted on by:

wingkwong profile



Consultant by day. Developer by night. AWS certified. Exploring #CloudNative currently.


Editor guide