Approach
Sorting and greedy selection
For Distribute Elements Into Two Arrays II, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 58 lines of Python from the credited upstream file 3072.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class FenwickTree:2 def __init__(self, n: int):3 self.sums = [0] * (n + 1)4 5 def add(self, i: int, delta: int) -> None:6 while i < len(self.sums):7 self.sums[i] += delta8 i += FenwickTree.lowbit(i)9 10 def get(self, i: int) -> int:11 summ = 012 while i > 0:13 summ += self.sums[i]14 i -= FenwickTree.lowbit(i)15 return summ16 17 @staticmethod18 def lowbit(i: int) -> int:19 return i & -i20 21 22class Solution:23 def resultArray(self, nums: list[int]) -> list[int]:24 arr1 = []25 arr2 = []26 ranks = self._getRanks(nums)27 tree1 = FenwickTree(len(ranks))28 tree2 = FenwickTree(len(ranks))29 30 def add(num: int, arr: list[int], tree: FenwickTree) -> None:31 arr.append(num)32 tree.add(ranks[num], 1)33 34 add(nums[0], arr1, tree1)35 add(nums[1], arr2, tree2)36 37 for i in range(2, len(nums)):38 greaterCount1 = len(arr1) - tree1.get(ranks[nums[i]])39 greaterCount2 = len(arr2) - tree2.get(ranks[nums[i]])40 if greaterCount1 > greaterCount2:41 add(nums[i], arr1, tree1)42 elif greaterCount1 < greaterCount2:43 add(nums[i], arr2, tree2)44 elif len(arr1) > len(arr2):45 add(nums[i], arr2, tree2)46 else:47 add(nums[i], arr1, tree1)48 49 return arr1 + arr250 51 def _getRanks(self, nums: list[int]) -> dict[int, int]:52 ranks = collections.Counter()53 rank = 054 for num in sorted(set(nums)):55 rank += 156 ranks[num] = rank57 return ranks58