Leetcode 949: Largest Time for Given Digits

grid47
grid47
Exploring patterns and algorithms
Aug 4, 2024 5 min read

Given an array of 4 digits, your task is to form the latest possible 24-hour time using each digit exactly once. The time is represented in the format ‘HH:MM’ where ‘HH’ is between 00 and 23, and ‘MM’ is between 00 and 59. If no valid time can be formed, return an empty string.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of integers representing 4 digits.
Example: Input: arr = [9, 1, 2, 4]
Constraints:
• The array will always have exactly 4 digits.
• Each digit will be between 0 and 9.
Output: The output should be the latest valid time in the format 'HH:MM'. If no valid time can be formed, return an empty string.
Example: Output: '21:49'
Constraints:
• The returned string should be in the format 'HH:MM'.
Goal: The goal is to generate all possible times using the given digits and return the latest valid time.
Steps:
• 1. Sort the digits in descending order to try the largest possible times first.
• 2. Try all permutations of the digits to form potential times.
• 3. For each permutation, check if the resulting time is valid (HH:MM format).
• 4. Return the latest valid time, or an empty string if none can be formed.
Goal: Constraints ensure that the solution can handle small arrays efficiently.
Steps:
• The input array will always contain exactly 4 digits.
• Each digit will be in the range [0, 9].
Assumptions:
• The digits provided are valid integers between 0 and 9.
Input: Input: arr = [9, 1, 2, 4]
Explanation: The largest valid time possible from these digits is '21:49'. The other permutations are not valid 24-hour times.

Input: Input: arr = [3, 3, 3, 2]
Explanation: The largest valid time possible is '23:33'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus