Skip to problem
←

Count of Smaller Numbers After Self

Hard 0 attempts

You're given an integer array nums. Build an array counts where counts[i] tells you how many elements located after index i are smaller than nums[i].

Function contract

Implement countSmaller(nums), where nums is an integer array.

Output: An array counts of the same length, where counts[i] is the number of indices j > i with nums[j] < nums[i]. Equal values are not counted.

Example 1

Input
nums = [5,2,6,1]
Output
[2,1,1,0]

Explanation: After 5, the smaller values are 2 and 1; after 2, only 1; after 6, only 1; after the final element, none.

Example 2

Input
nums = [2,2,1]
Output
[1,1,0]
Constraints
  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

Merge Sort with Index Tracking

Merge the index ranges in descending value order while retaining original indices. When a left value exceeds the current right value, it also exceeds all remaining right values, so add hi - j to its count. On equality, take the right value first without increasing the count; equal values must not count as smaller.

javascript
function countSmaller(nums) {
  const n = nums.length,
    counts = Array(n).fill(0);
  const indices = nums.map((_, i) => i);
  function mergeSort(lo, hi) {
    if (hi - lo <= 1) return;
    const mid = (lo + hi) >> 1;
    mergeSort(lo, mid);
    mergeSort(mid, hi);
    const temp = [];
    let i = lo,
      j = mid;
    while (i < mid && j < hi) {
      if (nums[indices[i]] > nums[indices[j]]) {
        counts[indices[i]] += hi - j;
        temp.push(indices[i++]);
      } else temp.push(indices[j++]);
    }
    while (i < mid) temp.push(indices[i++]);
    while (j < hi) temp.push(indices[j++]);
    for (let k = lo; k < hi; k++) indices[k] = temp[k - lo];
  }
  mergeSort(0, n);
  return counts;
}

Time: O(n log n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript