- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- Apply updates and combine the affected nodes to answer each query.
Code notes
- 107 lines of Python from the credited upstream file longest-balanced-subarray-i.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Count the build once, then multiply the logarithmic update or query path by the number of 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 Solution(object):6 def longestBalanced(self, nums):7 """8 :type nums: List[int]9 :rtype: int10 """11 class SegmentTree(object):12 def __init__(self, N):13 self.min = [0]*(1<<((N-1).bit_length()+1))14 self.max = [0]*(1<<((N-1).bit_length()+1))15 self.base = len(self.min)>>116 self.lazy = [0]*self.base17 18 def __apply(self, x, val):19 self.min[x] += val20 self.max[x] += val21 if x < self.base:22 self.lazy[x] += val23 24 def __push(self, x):25 for h in reversed(xrange(1, x.bit_length())):26 y = x>>h27 if self.lazy[y]:28 self.__apply(y<<1, self.lazy[y])29 self.__apply((y<<1)|1, self.lazy[y])30 self.lazy[y] = 031 32 def update(self, L, R, h): 33 def pull(x):34 while x > 1:35 x >>= 136 self.min[x] = self.min[x<<1] if self.min[x<<1] < self.min[(x<<1)|1] else self.min[(x<<1)|1]37 self.max[x] = self.max[x<<1] if self.max[x<<1] > self.max[(x<<1)|1] else self.max[(x<<1)|1]38 if self.lazy[x]:39 self.min[x] += self.lazy[x]40 self.max[x] += self.lazy[x]41 42 L += self.base43 R += self.base44 L0, R0 = L, R45 while L <= R:46 if L & 1: 47 self.__apply(L, h)48 L += 149 if R & 1 == 0: 50 self.__apply(R, h)51 R -= 152 L >>= 153 R >>= 154 pull(L0)55 pull(R0)56 57 def binary_search(self, x):58 i = 159 while not i >= self.base:60 if self.lazy[i]:61 self.__apply(i<<1, self.lazy[i])62 self.__apply((i<<1)|1, self.lazy[i])63 self.lazy[i] = 064 i <<= 165 if not self.min[i] <= x <= self.max[i]:66 i |= 167 return i-self.base 68 69 n = len(nums)+170 st = SegmentTree(n)71 result = curr = 072 lookup = {}73 for i, x in enumerate(nums, 1):74 d = +1 if x&1 else -175 if x in lookup:76 st.update(lookup[x], n-1, -d)77 curr -= d78 curr += d79 lookup[x] = i80 st.update(lookup[x], n-1, +d)81 l = i-st.binary_search(curr)82 if l > result:83 result = l84 return result85 86 87888990class Solution2(object):91 def longestBalanced(self, nums):92 """93 :type nums: List[int]94 :rtype: int95 """96 result = 097 for left in xrange(len(nums)):98 curr = 099 lookup = set()100 for right in xrange(left, len(nums)):101 if nums[right] not in lookup:102 lookup.add(nums[right])103 curr += 1 if nums[right]&1 else -1104 if curr == 0:105 result = max(result, right-left+1)106 return result107