Algorithm/NeetCode

Check If a String Contains All Binary Codes of Size K

Tony Lim 2024. 11. 9. 13:04
728x90

https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/

 

class Solution:
    def hashAllCodes(self, s: str, k: int) -> bool:
        codeSet = set()

        for i in range(len(s) -k + 1):
            codeSet.add(s[i:i + k])
        return len(codeSet) == 2 ** k

A naive approach would be to iterate over the string for each given binary combination.

But instead, we can use a set to check whether the number of consecutive substrings of length k is equal to the number of binary combinations of length k.

 

 

728x90

'Algorithm > NeetCode' 카테고리의 다른 글

First Missing Positive  (1) 2024.11.12
Non-decreasing Array  (2) 2024.11.11
Range Sum Query 2D - Immutable  (0) 2024.11.10
Insert Delete GetRandom O(1)  (0) 2024.11.08
Repeated DNA Sequences  (0) 2024.11.07