✅ Java Solution | Easy to understand
CODE\nJava []\nprivate int counter(ArrayList<Node> list, int val, int size){\n\tint res = size, l=0, r=size-1;\n\twhile(l <= r){\n\t\tint mid = l + (r-l)/2;\n\t
## **CODE**\n```Java []\nprivate int counter(ArrayList<Node> list, int val, int size){\n\tint res = size, l=0, r=size-1;\n\twhile(l <= r){\n\t\tint mid = l + (r-l)/2;\n\t\tNode curr = list.get(mid);\n\t\tif(curr.val > val){\n\t\t\tres = mid;\n\t\t\tr = mid-1;\n\t\t}else {\n\t\t\tl = mid+1;\n\t\t}\n\t}\n\treturn res;\n}\n\nclass Node {\n\tint idx;\n\tint val;\n\tNode(int v, int i){\n\t\tidx = i;\n\t\tval = v;\n\t}\n}\n\npublic int[] resultArray(int[] nums) {\n\tArrayList<Node> arr1 = new ArrayList<>();\n\tArrayList<Node> arr2 = new ArrayList<>();\n\n\tarr1.add(new Node(nums[0], 0));\n\tarr2.add(new Node(nums[1], 0));\n\tint size1 = 1, size2 = 1;\n\n\tint n = nums.length;\n\tfor(int i=2; i<n; i++){\n\t\tint idx1 = counter(arr1, nums[i], size1);\n\t\tint idx2 = counter(arr2, nums[i], size2);\n\n\t\tint val1=size1-idx1, val2=size2-idx2;\n\n\t\tif(val1 > val2) {\n\t\t\tarr1.add(idx1, new Node(nums[i], size1));\n\t\t\tsize1++;\n\n\t\t}else if(val1 < val2) {\n\t\t\tarr2.add(idx2, new Node(nums[i], size2));\n\t\t\tsize2++;\n\n\t\t}else {\n\t\t\tif(size1 <= size2){\n\t\t\t\tarr1.add(idx1, new Node(nums[i], size1));\n\t\t\t\tsize1++;\n\n\t\t\t}else {\n\t\t\t\tarr2.add(idx2, new Node(nums[i], size2));\n\t\t\t\tsize2++;\n\t\t\t}\n\t\t}\n\t}\n\n\tint res[] = new int[n];\n\tint i=0, k=0;\n\twhile(i < size1){\n\t\tNode curr = arr1.get(i++);\n\t\tres[curr.idx] = curr.val;\n\t}\n\ti=0;\n\twhile(i < size2){\n\t\tNode curr = arr2.get(i++);\n\t\tres[size1+curr.idx] = curr.val;\n\t}\n\n\treturn res;\n}\n```
['Array', 'Binary Tree', 'Java']