Problem solution · Python

Longest Balanced Subarray I

Longest Balanced Subarray I: a Python solution using segment tree or range structure. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Segment tree or range structure
Source
Kamyu LeetCode Solutions
Length
107 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

Segment tree or range structure

For Longest Balanced Subarray I, the implementation stores interval information in a range-query data structure so updates and queries avoid rescanning the full input.

  1. Choose the aggregate stored for each interval or prefix.
  2. Build or initialize the structure from the input.
  3. 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.

Source

Code and credit

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

Full codeLongest Balanced Subarray I · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(nlogn)# Space: O(n) # segment tree, binary search, prefix sumclass Solution(object):    def longestBalanced(self, nums):        """        :type nums: List[int]        :rtype: int        """        class SegmentTree(object):            def __init__(self, N):                self.min = [0]*(1<<((N-1).bit_length()+1))                self.max = [0]*(1<<((N-1).bit_length()+1))                self.base = len(self.min)>>1                self.lazy = [0]*self.base                            def __apply(self, x, val):                self.min[x] += val                self.max[x] += val                if x < self.base:                    self.lazy[x] += val             def __push(self, x):                for h in reversed(xrange(1, x.bit_length())):                    y = x>>h                    if self.lazy[y]:                        self.__apply(y<<1, self.lazy[y])                        self.__apply((y<<1)|1, self.lazy[y])                        self.lazy[y] = 0             def update(self, L, R, h):  # Time: O(logN), Space: O(N)                def pull(x):                    while x > 1:                        x >>= 1                        self.min[x] = self.min[x<<1] if self.min[x<<1] < self.min[(x<<1)|1] else self.min[(x<<1)|1]                        self.max[x] = self.max[x<<1] if self.max[x<<1] > self.max[(x<<1)|1] else self.max[(x<<1)|1]                        if self.lazy[x]:                            self.min[x] += self.lazy[x]                            self.max[x] += self.lazy[x]                 L += self.base                R += self.base                L0, R0 = L, R                while L <= R:                    if L & 1:  # is right child                        self.__apply(L, h)                        L += 1                    if R & 1 == 0:  # is left child                        self.__apply(R, h)                        R -= 1                    L >>= 1                    R >>= 1                pull(L0)                pull(R0)             def binary_search(self, x):                i = 1                while not i >= self.base:                    if self.lazy[i]:                        self.__apply(i<<1, self.lazy[i])                        self.__apply((i<<1)|1, self.lazy[i])                        self.lazy[i] = 0                    i <<= 1                    if not self.min[i] <= x <= self.max[i]:                        i |= 1                return i-self.base              n = len(nums)+1        st = SegmentTree(n)        result = curr = 0        lookup = {}        for i, x in enumerate(nums, 1):            d = +1 if x&1 else -1            if x in lookup:                st.update(lookup[x], n-1, -d)                curr -= d            curr += d            lookup[x] = i            st.update(lookup[x], n-1, +d)            l = i-st.binary_search(curr)            if l > result:                result = l        return result  # Time:  O(n^2)# Space: O(n)# brute forceclass Solution2(object):    def longestBalanced(self, nums):        """        :type nums: List[int]        :rtype: int        """        result = 0        for left in xrange(len(nums)):            curr = 0            lookup = set()            for right in xrange(left, len(nums)):                if nums[right] not in lookup:                    lookup.add(nums[right])                    curr += 1 if nums[right]&1 else -1                if curr == 0:                    result = max(result, right-left+1)        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 ↗