![]() |
VOOZH | about |
Given an unsorted array arr[] of distinct integers, construct another array countSmaller[] such that countSmaller[i] contains the count of smaller elements on the right side of each element arr[i] in the array.
Examples:
Input: arr[] = [12, 1, 2, 3, 0, 11, 4]
Output: [6, 1, 1, 1, 0, 1, 0]Input: arr[] = [5, 4, 3, 2, 1]
Output: [4, 3, 2, 1, 0]Input: arr[] = [1, 2, 3, 4, 5]
Output: [0, 0, 0, 0, 0]
Table of Content
The idea is to use nested loops, where for each element we check how many elements on its right side are smaller than it.
6 1 1 1 0 1 0
The idea is to use a modified merge sort. We store both element values and their original indices. While merging, we count how many elements from the right half are smaller and add this count to the corresponding index’s result.
Steps to solve the problem:
6 1 1 1 0 1 0