Latest Time You Can Obtain After Replacing Characters

Problem Description

Ah, the classic dilemma of time management! Imagine you’re late for a meeting, and your watch is a bit shy about revealing the time. Instead, it has decided to play a game of hide-and-seek with its digits, replacing some of them with question marks. Your task, should you choose to accept it, is to figure out the latest possible time that could be displayed on this elusive watch.

In the world of LeetCode, this problem is known as “Latest Time You Can Obtain After Replacing Characters.” You’re given a string representing a time in the format “HH:MM”, where some digits may be replaced by ‘?’. Your mission, should you choose to accept it, is to replace the ‘?’ characters with the highest possible digits to form the latest valid time.

For example, if your watch says “2?:3?”, you could replace the ‘?’s to get “23:59”, which is the latest time possible. But if it says “??:??”, you could go all out and make it “23:59” as well.

Code Solution


class Solution {
    public String findLatestTime(String s) {
        char[] ans = s.toCharArray();
        if (s.charAt(0) == '?')
            ans[0] = s.charAt(1) == '?' || s.charAt(1) < '2' ? '1' : '0';
        if (s.charAt(1) == '?')
            ans[1] = ans[0] == '1' ? '1' : '9';
        if (s.charAt(3) == '?')
            ans[3] = '5';
        if (s.charAt(4) == '?')
            ans[4] = '9';
        return new String(ans);
    }
}

Approach

The approach taken in this solution is straightforward yet clever. The code checks each character of the time string. If it encounters a '?', it replaces it with the highest possible digit that would still yield a valid time.

  1. For the first character (hour's tens place), it checks the second character to decide whether to place '1' or '0'.
  2. For the hour's units place, it ensures that if the tens place is '1', it can safely place '1' there; otherwise, it goes for '9'.
  3. The minutes are simpler: the tens place is always '5', and the units place is '9'.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(1) - The solution processes a fixed number of characters (5) regardless of input size.
Space Complexity O(1) - The space used does not depend on the input size, as we are only using a few variables.

Real-World Example

Imagine you’re at a party, and your friend’s phone is stuck on "??:??". You want to impress everyone by telling them the latest time possible. You quickly deduce that the best you can do is "23:59". Just like that, you’ve saved the day!

Similar Problems

If you enjoyed this problem, you might also like these:

  • 2-Sum Solution in Java
  • 3-Sum Solution in Java