SortedList + Binary Search Python
\n\n# Code\n\nfrom sortedcontainers import SortedList\nclass Solution:\n    def resultArray(self, nums: List[int]) -> List[int]:\n        a1 = SortedList([nums[
\n\n# Code\n```\nfrom sortedcontainers import SortedList\nclass Solution:\n    def resultArray(self, nums: List[int]) -> List[int]:\n        a1 = SortedList([nums[0]])\n        a2 = SortedList([nums[1]])\n        lna1 = 1\n        lna2 = 1\n        n = len(nums)\n        r1 = [nums[0]]\n        r2 = [nums[1]]\n\n        for i in range(2, n):\n            grt1 = lna1 - a1.bisect_right(nums[i])\n            grt2 = lna2 - a2.bisect_right(nums[i])\n            if grt1 > grt2:\n                a1.add(nums[i])\n                r1.append(nums[i])\n                lna1 += 1\n            elif grt1 < grt2:\n                a2.add(nums[i])\n                r2.append(nums[i])\n                lna2 += 1\n            else:\n                if lna1 <= lna2:\n                    a1.add(nums[i])\n                    r1.append(nums[i])\n                    lna1 += 1\n                else:\n                    a2.add(nums[i])\n                    r2.append(nums[i])\n                    lna2 += 1\n        \n        return r1 + r2\n\n\n\n```
['Python3']