💡Swift - Optimal Solution - Binary Indexed Tree
Solution\nswift\nclass Solution {\n    func resultArray(_ nums: [Int]) -> [Int] {\n        // Building trees.\n        // Map indices of the sorted elements by 
# Solution\n```swift\nclass Solution {\n    func resultArray(_ nums: [Int]) -> [Int] {\n        // Building trees.\n        // Map indices of the sorted elements by their values, converted to 1-indexed.\n        let indicesMap = nums.sorted().enumerated().reduce(into: [:]) { $0[$1.element] = $1.offset + 1 }\n        let tree1 = FenwickTree(nums.count)\n        let tree2 = FenwickTree(nums.count)\n\n        // Initial state.\n        var arr1: [Int] = [nums[0]]\n        var arr2: [Int] = [nums[1]]\n        tree1.update(indicesMap[nums[0]]!, 1)\n        tree2.update(indicesMap[nums[1]]!, 1)\n        \n        // Distribute elements following the given criteria.\n        for num in nums[2...] {\n            let index = indicesMap[num, default: 0]\n            let gc1 = arr1.count - tree1.prefixSum(index)\n            let gc2 = arr2.count - tree2.prefixSum(index)\n            if gc1 > gc2 || (gc1 == gc2 && arr1.count <= arr2.count) {\n                arr1.append(num)\n                tree1.update(index, 1)\n            } else {\n                arr2.append(num)\n                tree2.update(index, 1)\n            }\n        }\n\n        return arr1 + arr2\n    }\n}\n\nclass FenwickTree {\n    var tree: [Int]\n    init(_ size: Int) {\n        tree = Array(repeating: 0, count: size + 1)\n    }\n    func update(_ index: Int, _ delta: Int) {\n        var index = index\n        while index < tree.count {\n            tree[index] += delta\n            index += index & -index\n        }\n    }\n    func prefixSum(_ index: Int) -> Int {\n        var index = index\n        var sum = 0\n        while index > 0 {\n            sum += tree[index]\n            index -= index & -index\n        }\n        return sum\n    }\n}\n```\n# Complexity\n- Time: $$O(n \\cdot logn)$$\n- Space: $$O(n)$$
['Binary Indexed Tree', 'Swift']