LeetCode 401: Binary Watch Solution

Master LeetCode problem 401 (Binary Watch), a easy 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.

401. Binary Watch

Problem Explanation

Explanation

To solve this problem, we can generate all possible combinations of hours and minutes where the number of turned on LEDs equals the given turnedOn. We iterate through all possible combinations of hours and minutes, count the number of set bits (turned on LEDs), and add the valid time to our result if the count matches turnedOn.

Algorithm

  1. Initialize an empty list to store the valid times.
  2. Iterate through all possible combinations of hours (0 to 11) and minutes (0 to 59).
  3. Count the number of set bits (turned on LEDs) in the binary representation of the hour and minute.
  4. If the total count of set bits equals turnedOn, format the time in HH:MM format and add it to the result list.
  5. Return the list of valid times.

Time Complexity

The time complexity of this algorithm is O(1) since the total number of valid times is limited to a constant number.

Space Complexity

The space complexity is also O(1) as we only store the resulting valid times.

Solution Code

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<String> readBinaryWatch(int turnedOn) {
        List<String> result = new ArrayList<>();
        for (int h = 0; h < 12; h++) {
            for (int m = 0; m < 60; m++) {
                if (Integer.bitCount(h) + Integer.bitCount(m) == turnedOn) {
                    result.add(String.format("%d:%02d", h, m));
                }
            }
        }
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 401 (Binary Watch)?

This page provides optimized solutions for LeetCode problem 401 (Binary Watch) 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 401 (Binary Watch)?

The time complexity for LeetCode 401 (Binary Watch) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 401 on DevExCode?

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

Back to LeetCode Solutions