LeetCode solutions

3350. Distribute Elements Into Two Arrays II

My accepted Python solution to LeetCode problem 3350, Distribute Elements Into Two Arrays II, running in 993ms.

  • Difficulty: Hard
  • Python
  • Runtime 993ms
  • Memory 36.8MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 993ms, memory 36.8MB, accepted 2026-01-01.

python
from sortedcontainers import SortedList

class Solution:
    def resultArray(self, nums: List[int]) -> List[int]:
        arr1 = [nums[0]]
        arr2 = [nums[1]]
        sorted1 = SortedList([nums[0]])
        sorted2 = SortedList([nums[1]])
        
        for i in range(2, len(nums)):
            num = nums[i]
            
            # Count elements greater than num in each array
            count1 = len(sorted1) - sorted1.bisect_right(num)
            count2 = len(sorted2) - sorted2.bisect_right(num)
            
            if count1 > count2:
                arr1.append(num)
                sorted1.add(num)
            elif count2 > count1:
                arr2.append(num)
                sorted2.add(num)
            elif len(arr1) <= len(arr2):
                arr1.append(num)
                sorted1.add(num)
            else:
                arr2.append(num)
                sorted2.add(num)
        
        return arr1 + arr2

Source