Largest Time for Given Digits — LeetCode 949 Python Solution
- Problem
- #949
- Pattern
- Backtracking
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59.
Example
- Input
- arr = [1,2,3,4]
- Output
- "23:41"
- Explanation
- The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest.
Python solution
class Solution:
def largestTimeFromDigits(self, arr: List[int]) -> str:
cnt = [0] * 10
for v in arr:
cnt[v] += 1
for h in range(23, -1, -1):
for m in range(59, -1, -1):
t = [0] * 10
t[h // 10] += 1
t[h % 10] += 1
t[m // 10] += 1
t[m % 10] += 1
if cnt == t:
return f'{h:02}:{m:02}'
return ''Complexity
| Measure | Complexity |
|---|---|
| Time | Exponential (worst case) |
| Space | O(depth) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 949. Largest Time for Given Digits is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 949. Largest Time for Given Digits?
- LeetCode 949. Largest Time for Given Digits is rated Medium on LeetCode.
- What topics does LeetCode 949. Largest Time for Given Digits cover?
- LeetCode 949. Largest Time for Given Digits is tagged Array, String, Backtracking and Enumeration on LeetCode.