Problem solution · Python

Find Subarray with Bitwise or Closest to K

Find Subarray with Bitwise or Closest to K: a Python solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Sliding window or two pointers
Source
Kamyu LeetCode Solutions
Length
76 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Find Subarray with Bitwise or Closest to K, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 76 lines of Python from the credited upstream file find-subarray-with-bitwise-or-closest-to-k.py.
  • The implementation visibly relies on sequence storage, ordered lookup.
  • No explicit loop blocks detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeFind Subarray with Bitwise or Closest to K · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(nlogr), r = max(nums)# Space: O(logr) # freq table, two pointers, sliding window, lc1521class BitCount(object):    def __init__(self, n):        self.__l = 0        self.__n = n        self.__count = [0]*n        def __iadd__(self, num):        self.__l += 1        base = 1        for i in xrange(self.__n):            if num&base:                self.__count[i] += 1            base <<= 1        return self     def __isub__(self, num):        self.__l -= 1        base = 1        for i in xrange(self.__n):            if num&base:                self.__count[i] -= 1            base <<= 1        return self     def bit_or(self):        num, base = 0, 1        for i in xrange(self.__n):            if self.__count[i]:                num |= base            base <<= 1        return num                     class Solution(object):    def minimumDifference(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: int        """        count = BitCount(max(nums).bit_length())        result, left = float("inf"), 0        for right in xrange(len(nums)):            count += nums[right]            while left <= right:                f = count.bit_or()                result = min(result, abs(f-k))                if f <= k:                    break                count -= nums[left]                left += 1        return result  # Time:  O(nlogr), r = max(nums)# Space: O(logr)# dp, lc1521class Solution2(object):    def minimumDifference(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: int        """        result, dp = float("inf"), set()  # at most O(logr) dp states        for x in nums:            dp = {x}|{f|x for f in dp}            for f in dp:                result = min(result, abs(f-k))        return result     

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗