- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- 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.
Use this to learn the idea, then write your own version.
123 45class BitCount(object):6 def __init__(self, n):7 self.__l = 08 self.__n = n9 self.__count = [0]*n10 11 def __iadd__(self, num):12 self.__l += 113 base = 114 for i in xrange(self.__n):15 if num&base:16 self.__count[i] += 117 base <<= 118 return self19 20 def __isub__(self, num):21 self.__l -= 122 base = 123 for i in xrange(self.__n):24 if num&base:25 self.__count[i] -= 126 base <<= 127 return self28 29 def bit_or(self):30 num, base = 0, 131 for i in xrange(self.__n):32 if self.__count[i]:33 num |= base34 base <<= 135 return num36 37 38class Solution(object):39 def minimumDifference(self, nums, k):40 """41 :type nums: List[int]42 :type k: int43 :rtype: int44 """45 count = BitCount(max(nums).bit_length())46 result, left = float("inf"), 047 for right in xrange(len(nums)):48 count += nums[right]49 while left <= right:50 f = count.bit_or()51 result = min(result, abs(f-k))52 if f <= k:53 break54 count -= nums[left]55 left += 156 return result57 58 59606162class Solution2(object):63 def minimumDifference(self, nums, k):64 """65 :type nums: List[int]66 :type k: int67 :rtype: int68 """69 result, dp = float("inf"), set() 70 for x in nums:71 dp = {x}|{f|x for f in dp}72 for f in dp:73 result = min(result, abs(f-k))74 return result75 76