Problem solution · Python

Fruits into Baskets II

Fruits into Baskets II: 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
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

Segment tree or range structure

For Fruits into Baskets II, 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

  • 76 lines of Python from the credited upstream file fruits-into-baskets-ii.py.
  • The implementation visibly relies on sequence storage.
  • 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 codeFruits into Baskets II · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(nlogn)# Space: O(n) # segment tree, binary searchclass Solution(object):    def numOfUnplacedFruits(self, fruits, baskets):        """        :type fruits: List[int]        :type baskets: List[int]        :rtype: int        """        class SegmentTree(object):            def __init__(self, N,                        build_fn=lambda _: 0,                        query_fn=lambda x, y: y if x is None else x if y is None else max(x, y),                        update_fn=lambda x: x):                self.tree = [None]*(2*2**((N-1).bit_length()))                self.base = len(self.tree)//2                self.query_fn = query_fn                self.update_fn = update_fn                for i in xrange(self.base, self.base+N):                    self.tree[i] = build_fn(i-self.base)                for i in reversed(xrange(1, self.base)):                    self.tree[i] = query_fn(self.tree[2*i], self.tree[2*i+1])             def update(self, i, h):                x = self.base+i                self.tree[x] = self.update_fn(h)                while x > 1:                    x //= 2                    self.tree[x] = self.query_fn(self.tree[x*2], self.tree[x*2+1])             def binary_search(self, x):                if self.tree[1] < x:                    return -1                i = 1                while not i >= self.base:                    if self.tree[2*i] >= x:                        i = 2*i                    else:                        i = 2*i+1                return i-self.base         def build(i):            return baskets[i]         st = SegmentTree(len(baskets), build_fn=build)        result = 0        for x in fruits:            i = st.binary_search(x)            if i == -1:                result += 1            else:                st.update(i, 0)        return result  # Time:  O(n^2)# Space: O(1)# brute forceclass Solution2(object):    def numOfUnplacedFruits(self, fruits, baskets):        """        :type fruits: List[int]        :type baskets: List[int]        :rtype: int        """        result = 0        for x in fruits:            i = next((i for i in xrange(len(baskets)) if baskets[i] >= x), -1)            if i ==-1:                result += 1            else:                baskets[i] = 0        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 ↗