#3072
Distribute Elements Into Two Arrays II
HardArrayBinary Indexed TreeSegment TreeSimulationBinary Indexed TreeSegment Tree
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
Using a data structure like a Binary Indexed Tree (BIT) allows us to efficiently count the number of elements greater than a given value while supporting quick updates as we build arr1 and arr2.
⚙️
Algorithm
3 steps- 1Step 1: Normalize the values in nums to fit into a range [1, n] for BIT usage.
- 2Step 2: Initialize a BIT to keep track of counts of elements in arr1 and arr2.
- 3Step 3: For each element in nums, use the BIT to get greaterCount for both arrays and append to the appropriate array.
solution.py42 lines
1class BIT:
2 def __init__(self, size):
3 self.size = size
4 self.tree = [0] * (size + 1)
5
6 def update(self, index, delta):
7 while index <= self.size:
8 self.tree[index] += delta
9 index += index & -index
10
11 def query(self, index):
12 total = 0
13 while index > 0:
14 total += self.tree[index]
15 index -= index & -index
16 return total
17
18def distributeElements(nums):
19 n = len(nums)
20 max_val = max(nums)
21 bit = BIT(max_val)
22 arr1 = [nums[0]]
23 arr2 = [nums[1]]
24 bit.update(nums[0], 1)
25 bit.update(nums[1], 1)
26 for i in range(2, n):
27 count1 = bit.query(max_val) - bit.query(nums[i])
28 count2 = bit.query(max_val) - bit.query(nums[i])
29 if count1 > count2:
30 arr1.append(nums[i])
31 bit.update(nums[i], 1)
32 elif count1 < count2:
33 arr2.append(nums[i])
34 bit.update(nums[i], 1)
35 else:
36 if len(arr1) < len(arr2):
37 arr1.append(nums[i])
38 bit.update(nums[i], 1)
39 else:
40 arr2.append(nums[i])
41 bit.update(nums[i], 1)
42 return arr1 + arr2ℹ
Complexity note: The BIT allows us to update and query counts in logarithmic time, leading to an overall complexity of O(n log n) for processing all elements.
- 1Using efficient data structures can significantly reduce time complexity.
- 2Understanding how to normalize data for specific algorithms is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.