LeetCode 949: Largest Time for Given Digits Solution

Master LeetCode problem 949 (Largest Time for Given Digits), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

949. Largest Time for Given Digits

Problem Explanation

Explanation

To solve this problem, we need to generate all possible permutations of the given digits (arr) and then filter out the valid times. We can iterate over all possible permutations and check if they form a valid time. To check validity, we need to ensure that the first two digits form a valid hour (00-23) and the last two digits form a valid minute (00-59). We should also find the latest valid time among all possibilities.

  • Algorithmic Idea:

    1. Generate all permutations of the given digits.
    2. Check each permutation to see if it forms a valid time.
    3. Keep track of the latest valid time found.
  • Time Complexity:

    • Generating all permutations: O(1) as there are only 24 permutations of 4 elements.
    • Validating each permutation: O(1) as we are just checking 24 permutations.
    • Overall time complexity: O(1).
  • Space Complexity:

    • Storing permutations: O(1) as we are not storing all permutations explicitly.
    • Overall space complexity: O(1).

Solution Code

class Solution {
    public String largestTimeFromDigits(int[] arr) {
        String ans = "";
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if (i == j) continue;
                for (int k = 0; k < 4; k++) {
                    if (i == k || j == k) continue;
                    int l = 6 - i - j - k;
                    String hh = "" + arr[i] + arr[j];
                    String mm = "" + arr[k] + arr[l];
                    String time = hh + ":" + mm;
                    if (hh.compareTo("24") < 0 && mm.compareTo("60") < 0 && time.compareTo(ans) > 0) {
                        ans = time;
                    }
                }
            }
        }
        return ans;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 949 (Largest Time for Given Digits)?

This page provides optimized solutions for LeetCode problem 949 (Largest Time for Given Digits) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 949 (Largest Time for Given Digits)?

The time complexity for LeetCode 949 (Largest Time for Given Digits) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 949 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 949 in Java, C++, or Python.

Back to LeetCode Solutions