07. Count of Smaller Numbers After Self

Difficulty:HardPattern:Modified Merge SortTime:O(n log n)Space:O(n)

Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].

How It Works & Algorithmic Design

Solves using Modified Merge Sort with Right-Side Inversion Counting:

  1. Index Tracking: Create array of index pairs [value, originalIndex].
  2. Merge Step: Merge sorted left half and right half:
    • When picking element from left half because left[i].val <= right[j].val:
      • Accumulate count: counts[left[i].index] += rightCount (number of elements taken from right half so far).
    • When picking element from right half: increment rightCount++.
  3. Return: Populated counts array.

Why This Approach Works Best

Merge sort counts inversions across array splits in optimal $O(n \log n)$ time and $O(n)$ space.

Example Walkthrough

Input

[5, 2, 6, 1]

Target array.

Right Smaller Counts

5 has 2 smaller (2,1); 2 has 1 smaller (1); 6 has 1 smaller (1); 1 has 0

Count per element.

Output

[2, 1, 1, 0]

Result array.

Answer: Count Smaller Numbers Merge Sort implementation

function countSmaller(nums) {
  const n = nums.length;
  const counts = new Array(n).fill(0);
  const items = nums.map((val, idx) => ({ val, idx }));
  function mergeSort(arr) {
    if (arr.length <= 1) return arr;
    const mid = Math.floor(arr.length / 2);
    const left = mergeSort(arr.slice(0, mid));
    const right = mergeSort(arr.slice(mid));
    const merged = [];
    let i = 0, j = 0, rightCount = 0;
    while (i < left.length && j < right.length) {
      if (right[j].val < left[i].val) {
        rightCount++;
        merged.push(right[j++]);
      } else {
        counts[left[i].idx] += rightCount;
        merged.push(left[i++]);
      }
    }
    while (i < left.length) {
      counts[left[i].idx] += rightCount;
      merged.push(left[i++]);
    }
    while (j < right.length) merged.push(right[j++]);
    return merged;
  }
  mergeSort(items);
  return counts;
}

Count right-side smaller element inversions during Merge Sort index array consolidation.

Key Takeaways
  • Tracks original indices using value-index object pairs.

  • Increments rightCount whenever smaller element from right sub-array is merged first.

  • Optimal $O(n \log n)$ runtime.