← Home

949. Largest Time for Given Digits

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
backtrackingC++Markdown
949

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 949. Largest Time for Given Digits, the solution in this repository is mainly a backtracking solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: backtracking, greedy.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are largestTimeFromDigits, permute.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Largest Time for Given Digits.
02//Memory Usage: 9.5 MB, less than 80.82% of C++ online submissions for Largest Time for Given Digits.
03class Solution {
04public:
05    string largestTimeFromDigits(vector<int>& A) {
06        /*
07        ??:??
08        first: 0,1,2
09        second: 0-9 when first is 0,1; 0-3 when first is 2
10        third: 0-5
11        fourth: 0-9
12        */
13        sort(A.begin(), A.end());
14        
15        int se1_count = 0, se2_count = 0, se3_count = 0, se5_count = 0;
16        
17        for(int e: A){
18            if(e <= 1) ++se1_count;
19            if(e <= 2) ++se2_count;
20            if(e <= 3) ++se3_count;
21            if(e <= 5) ++se5_count;
22        }
23
24        if(se2_count < 1 || se5_count < 2){
25            return "";
26        }
27
28        string ans;
29        if(A[se2_count-1] == 2 && se3_count-1 >= 1 && se5_count - 2 >= 1){
30            //we can build 2?:??
31            ans += A[se2_count-1] + '0';
32            A.erase(A.begin()+se2_count-1);
33            --se3_count;
34            --se5_count;
35            // cout << ans << endl;
36
37            ans += A[se3_count-1] + '0';
38            A.erase(A.begin()+se3_count-1);
39            --se5_count;
40
41            ans += ':';
42            // cout << ans << endl;
43
44            ans += A[se5_count-1] + '0';
45            A.erase(A.begin()+se5_count-1);
46            // cout << ans << endl;
47
48            ans += A[0] + '0';
49            // cout << ans << endl;
50            return ans;
51        }else if(se1_count < 1){
52            //cannot build "0?:??" or "1?:??"
53            return "";
54        }
55        
56        ans += A[se1_count-1] + '0';
57        A.erase(A.begin()+se1_count-1);
58        --se2_count;
59        --se3_count;
60        --se5_count;
61        
62        // cout << ans << endl;
63
64        ans += A.back() + '0';
65        if(A.back() <= 5) --se5_count;
66        A.pop_back();
67        // cout << ans << endl;
68
69        ans += ':';
70
71        // cout << "se5: " << se5_count << endl;
72        ans += A[se5_count-1] + '0';
73        A.erase(A.begin()+se5_count-1);
74        // cout << ans << endl;
75
76        ans += A[0] + '0';
77        // cout << ans << endl;
78
79        return ans;
80    }
81};
82
83//use built-in permutation function
84//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Largest Time for Given Digits.
85//Memory Usage: 9.4 MB, less than 97.80% of C++ online submissions for Largest Time for Given Digits.
86//time: O(1), space: O(1), because for a length 4 array, its permutation count is a constant
87class Solution {
88public:
89    string largestTimeFromDigits(vector<int>& A) {
90        int max_time = -1;
91        
92        sort(A.begin(), A.end());
93        
94        do{
95            int hour = A[0]*10 + A[1];
96            int minute = A[2]*10 + A[3];
97            if(hour < 24 && minute < 60){
98                int time = hour*60+minute;
99                max_time = max(max_time, time);
100            }
101        }while(next_permutation(A.begin(), A.end()));
102        
103        if(max_time == -1){
104            return "";
105        }
106        
107        ostringstream strstream;
108        strstream << setw(2) << setfill('0') << max_time/60 <<
109            ":" << setw(2) << setfill('0') << max_time%60;
110        
111        return strstream.str();
112    }
113};
114
115//backtracking, permutation
116//Runtime: 4 ms, faster than 79.21% of C++ online submissions for Largest Time for Given Digits.
117//Memory Usage: 9.5 MB, less than 78.33% of C++ online submissions for Largest Time for Given Digits.
118//time: O(1), space: O(1)
119class Solution {
120public:
121    int max_time;
122    
123    void permute(vector<int>& A, int cur){
124        int n = A.size();
125        
126        if(cur == n){
127            int hour = A[0]*10 + A[1];
128            int minute = A[2]*10 + A[3];
129            // cout << hour << ", " << minute << endl;
130            if(hour < 24 && minute < 60){
131                max_time = max(max_time, hour*60+minute);
132            }
133        }else{
134            /*
135            we want n-start+1 branches,
136            each branches first char are different
137            next starts from "cur",
138            because we want the first branch's first char to be "cur"
139            */
140            for(int next = cur; next < n; ++next){
141                // cout << "swap: " << cur << " and " << next << endl;
142                swap(A[cur], A[next]);
143                //in next recursion, start from the next position
144                permute(A, cur+1);
145                swap(A[cur], A[next]);
146            }
147        }
148    }
149    
150    string largestTimeFromDigits(vector<int>& A) {
151        max_time = -1;
152        
153        permute(A, 0);
154        
155        if(max_time == -1) return "";
156        
157        ostringstream strstream;
158        strstream << setw(2) << setfill('0') << max_time/60 <<
159            ":" << setw(2) << setfill('0') << max_time%60;
160        return strstream.str();
161    }
162};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.