Binary Watch Problem

Problem

A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.

  • For example, the below binary watch reads "4:51".

Given an integer turnedOn which represents the number of LEDs that are currently on (ignoring the PM), return all possible times the watch could represent. You may return the answer in any order.

The hour must not contain a leading zero.

  • For example, "01:00" is not valid. It should be "1:00".

The minute must consist of two digits and may contain a leading zero.

  • For example, "10:2" is not valid. It should be "10:02".

Examples

Example 1:

Input:
turnedOn = 1
Output:
 ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]

Example 2:

Input:
turnedOn = 9
Output:
 []

Solution

Method 1 - Iteration with bit counts

We know that all the numbers in binary watch have only 1 bit set. For eg. take the value 4 it is represented as 1000. Similarly, take the value 2, it is just 10. turnedOn in total should be equal to number of bits which can be set. Then the idea is simple - iterate on hours and seconds - collect those times with correct number of 1 bits. For eg. when turnedOn = 1, we know that

Code

C++
class Solution {
public:
    vector<string> readBinaryWatch(int turnedOn) {
        vector<string> ans;
        for (int i = 0; i < 12; ++i) {
            for (int j = 0; j < 60; ++j) {
                if (__builtin_popcount(i) + __builtin_popcount(j) == turnedOn) {
                    ans.push_back(to_string(i) + ":" + (j < 10 ? "0" : "") + to_string(j));
                }
            }
        }
        return ans;
    }
};
Go
func readBinaryWatch(turnedOn int) []string {
	var ans []string
	for i := 0; i < 12; i++ {
		for j := 0; j < 60; j++ {
			if bits.OnesCount(uint(i))+bits.OnesCount(uint(j)) == turnedOn {
				ans = append(ans, fmt.Sprintf("%d:%02d", i, j))
			}
		}
	}
	return ans
}
Java
class Solution {
    public List<String> readBinaryWatch(int turnedOn) {
        List<String> ans = new ArrayList<>();
        for (int i = 0; i < 12; ++i) {
            for (int j = 0; j < 60; ++j) {
                if (Integer.bitCount(i) + Integer.bitCount(j) == turnedOn) {
                    ans.add(String.format("%d:%02d", i, j));
                }
            }
        }
        return ans;
    }
}
Python
class Solution:
    def readBinaryWatch(self, turnedOn: int) -> List[str]:
        return [
            '{:d}:{:02d}'.format(i, j)
            for i in range(12)
            for j in range(60)
            if (bin(i) + bin(j)).count('1') == turnedOn
        ]

Complexity

  • Time: O(12*60) = O(1)
  • Space: O(1)

Method 2 - Backtracking using DFS

Another way is we can create helper function to find all the answers, and backtrack when we find some strange input.

Code

Java
class Solution {
	private int[] hours = {1, 2, 4, 8};
	private int[] minutes = {1, 2, 4, 8, 16, 32};
	Set<String> set = new HashSet<>();
    
    public List<String> readBinaryWatch(int turnedOn) {
		helper(0, 0, 0, 0, turnedOn);
		return new ArrayList<>(set);
    }
	private void helper(int hourIdx, int minuteIdx, int h, int m, int turnedOn) {
		if (h > 11 || m > 59 || turnedOn < 0) {
			return;
		}
		
		if (turnedOn == 0) {
			StringBuilder sb = new StringBuilder();
			sb.append(h);
			sb.append(":");
			
			if (m / 10 == 0) {
				sb.append("0");
			}			
			sb.append(m);
			set.add(sb.toString());
			return;
		}

		for (int i = minuteIdx; i < minutes.length; i++) {
			 helper(h, i + 1,  h, m + minutes[i], turnedOn - 1);
		}

		for (int i = hourIdx; i < hours.length; i++) {
			helper(i + 1, minuteIdx, h + hours[i], m, turnedOn - 1);
		}
	}
}

Complexity

  • Time: O(10^turnedOn) - As we have 2 input arrays - hours and minutes and we do dfs on their indices.
  • Space: O(1)