Largest Time for Given Digits

More deceiving than it looks: https://leetcode.com/problems/largest-time-for-given-digits/description/

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: ""

One way is to use backtracking, here is the gist of it:

  • First sort the array in descending order. This will guarantee that the first solution found is the optimal
  • Backtrack it
  • For each index from 0..3, you'll need to use different rules based on the time structure. For example, for position 0, it is only allowed to have digits 2..0. And so on
  • As you backtrack, if you find a solution return
  • Given the small size of the input (4), even the exponential should do it (think about 4^4, or 2^8, that's 256....)
Code is down below, cheers, Marcelo.


public class Solution
{
 public string LargestTimeFromDigits(int[] A)
 {
 Array.Sort(A);
 int[] nums = new int[A.Length];
 for (int i = 0; i < nums.Length; i++) nums[i] = A[A.Length - i - 1];
 Hashtable used = new Hashtable();
 string retVal = "";
 if (LargestTimeFromDigits(nums, 0, used, "", ref retVal)) return retVal;
 return "";
 }
 private bool LargestTimeFromDigits(int[] nums,
 int currentIndex,
 Hashtable used,
 string current,
 ref string retVal)
 {
 if (currentIndex >= nums.Length)
 {
 retVal = current;
 return true;
 }
 switch (currentIndex)
 {
 case 0:
 for (int i = 0; i < nums.Length; i++)
 {
 if (!used.ContainsKey(i) && nums[i] >= 0 && nums[i] <= 2)
 {
 used.Add(i, true);
 if (LargestTimeFromDigits(nums, currentIndex + 1, used, current + nums[i].ToString(), ref retVal)) return true;
 used.Remove(i); 
 }
 }
 break;
 case 1:
 for (int i = 0; i < nums.Length; i++)
 {
 if (!used.ContainsKey(i))
 {
 if (current.StartsWith("2"))
 {
 if (nums[i] >= 0 && nums[i] <= 3)
 {
 used.Add(i, true);
 if (LargestTimeFromDigits(nums, currentIndex + 1, used, current + nums[i].ToString() + ":", ref retVal)) return true;
 used.Remove(i);
 }
 }
 else
 {
 used.Add(i, true);
 if (LargestTimeFromDigits(nums, currentIndex + 1, used, current + nums[i].ToString() + ":", ref retVal)) return true;
 used.Remove(i);
 }
 }
 }
 break;
 case 2:
 for (int i = 0; i < nums.Length; i++)
 {
 if (!used.ContainsKey(i) && nums[i] >= 0 && nums[i] <= 5)
 {
 used.Add(i, true);
 if (LargestTimeFromDigits(nums, currentIndex + 1, used, current + nums[i].ToString(), ref retVal)) return true;
 used.Remove(i);
 }
 }
 break;
 case 3:
 for (int i = 0; i < nums.Length; i++)
 {
 if (!used.ContainsKey(i))
 {
 used.Add(i, true);
 if (LargestTimeFromDigits(nums, currentIndex + 1, used, current + nums[i].ToString(), ref retVal)) return true;
 used.Remove(i);
 }
 }
 break;
 }
 return false;
 }
}

Comments

  1. Wow, at moments like this I really appreciate Python having itertools module :)

    import itertools

    class Solution:
    def largestTimeFromDigits(self, A):
    return max(("%d%d:%d%d" % time for time in itertools.permutations(A) if time[:2] < (2, 4) and time[2] < 6), default="")

    Reply Delete

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. 🔍 Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...