1461. Check if a String Contains all Binary Codes of Size K - Explanation

Problem Link



1. Brute Force

class Solution:
    def hasAllCodes(self, s: str, k: int) -> bool:
        n = len(s)
        if n < (1 << k):
            return False

        for num in range(1 << k):
            binaryCode = format(num, f'0{k}b')
            if binaryCode not in s:
                return False

        return True

Time & Space Complexity

  • Time complexity: O(n2k)O(n * 2 ^ k)
  • Space complexity: O(k)O(k)

Where nn is the length of the string ss and kk is the length of the binary code.


2. Hash Set

class Solution:
    def hasAllCodes(self, s: str, k: int) -> bool:
        if len(s) < 2 ** k:
            return False

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

        return len(codeSet) == 2 ** k

Time & Space Complexity

  • Time complexity: O(nk)O(n * k)
  • Space complexity: O(2k)O(2 ^ k)

Where nn is the length of the string ss and kk is the length of the binary code.


3. Sliding Window

class Solution:
    def hasAllCodes(self, s: str, k: int) -> bool:
        n = len(s)
        if n < (1 << k):
            return False

        codeSet = [False] * (1 << k)
        cur = 0
        i = j = 0
        bit = k - 1
        while j < k:
            if s[j] == '1':
                cur |= (1 << bit)
            bit -= 1
            j += 1

        have = 1
        codeSet[cur] = True
        while j < n:
            if s[i] == '1':
                cur ^= (1 << (k - 1))
            i += 1

            cur <<= 1
            if s[j] == '1':
                cur |= 1
            j += 1

            if not codeSet[cur]:
                have += 1
                codeSet[cur] = True

        return have == (1 << k)

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(2k)O(2 ^ k)

Where nn is the length of the string ss and kk is the length of the binary code.


4. Sliding Window (Optimal)

class Solution:
    def hasAllCodes(self, s: str, k: int) -> bool:
        n = len(s)
        if n < (1 << k):
            return False

        codeSet = [False] * (1 << k)
        cur = 0
        have = 0

        for i in range(n):
            cur = ((cur << 1) & ((1 << k) - 1)) | (ord(s[i]) - ord('0'))

            if i >= k - 1:
                if not codeSet[cur]:
                    codeSet[cur] = True
                    have += 1

        return have == (1 << k)

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(2k)O(2 ^ k)

Where nn is the length of the string ss and kk is the length of the binary code.