#315

Count of Smaller Numbers After Self

Hard Merge sort with indexes

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

For every element, count how many elements to its right are strictly smaller.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: for each number, how many to its right are smaller?

Why this works: during merge sort, when a left element is placed, every right element already placed is smaller and was to its right. Add that count.

Example: [5, 2, 6, 1]

5 → (2, 1) = 22 → (1) = 16 → (1) = 11 → 0 → [2, 1, 1, 0]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Sorting the values directly — you lose track of which original position each count belongs to.

Solve on LeetCode ↗
Complexity
  • Time: O(n log n).
  • Space: O(n).
Topic: Sorting
🎬 Episodes 24–28: video coming soon