#1461
Check If a String Contains All Binary Codes of Size K
MediumHash TableStringBit ManipulationRolling HashHash FunctionHash MapSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a sliding window approach to efficiently track the unique substrings of length k. This avoids the overhead of repeatedly checking for duplicates.
⚙️
Algorithm
4 steps- 1Step 1: Create a set to store unique binary codes of length k.
- 2Step 2: Loop through the string with a sliding window of size k, adding each substring to the set.
- 3Step 3: If the size of the set equals 2^k at any point, return true.
- 4Step 4: If the loop completes and the size is not equal to 2^k, return false.
solution.py7 lines
1def hasAllCodes(s, k):
2 seen = set()
3 for i in range(len(s) - k + 1):
4 seen.add(s[i:i + k])
5 if len(seen) == 2 ** k:
6 return True
7 return len(seen) == 2 ** kℹ
Complexity note: The time complexity is O(n) because we only traverse the string once, and the space complexity is O(n) due to the storage of unique substrings in the set.
- 1The number of distinct binary codes of length k is always 2^k.
- 2Using a set allows for efficient tracking of unique substrings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.