Skip to content
Problem 315 · LeetCode 315(opens in a new tab)

Count of Smaller Numbers After Self

HardArrays

You get an integer array nums. For every position i, count how many numbers after position i are strictly less than nums[i].

Return those counts as an array of the same length, where entry i belongs to nums[i].

Example 1

Input:  nums = [7, 3, 8, 2, 3]
Output: [3, 1, 2, 0, 0]
Why:    after 7 come 3, 2 and 3; after the first 3 only 2 is smaller
2 more examples and the constraints

Example 2

Input:  nums = [-1]
Output: [0]
Why:    nothing comes after the only number

Example 3

Input:  nums = [4, 4, 4]
Output: [0, 0, 0]
Why:    equal numbers are not smaller

Constraints

  • 1 ≤ length of nums ≤ 100,000
  • −10,000 ≤ nums[i] ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check every pairO(n²)
  2. Fenwick tree from the rightO(n log V)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbersVerdict
Check every pairO(n²)
Too slow; about 5 billion checks
Fenwick tree from the rightO(n log V)
Best; about 3 million steps

n = length of nums, V = 20,001 possible values. A merge sort that counts right-side numbers passing to the left also runs in O(n log n).

Edge cases to test

  • One number. [−1] gives [0]: nothing comes after it.
  • Equal numbers. [4, 4, 4] gives all zeros, because equal is not smaller.
  • Negative values. Shift by 10,001 so every value maps to an index of at least 1.
  • Sorted from high to low. [4, 3, 2, 1] gives [3, 2, 1, 0], the largest counts possible.

Common mistakes

  • Counting equal numbers as smaller by summing up to nums[i] instead of nums[i] − 1.
  • Adding nums[i] to the tree before querying, so it counts itself.
  • Using a value as a Fenwick index without shifting, so 0 and negative values break the loop.

How to talk through it

  1. 1Clarify. Strictly smaller, or smaller or equal? What range can the values take? How long is the array?
  2. 2Give the brute force. Two loops over all pairs, O(n²), too slow at 100,000.
  3. 3Change the direction. From the right, the numbers already seen are exactly the ones after i, so the question becomes a count of seen values below nums[i].
  4. 4Pick the structure. That is a prefix sum over value counts with updates: a Fenwick tree does both in O(log V).
  5. 5Test out loud. Run [−1], [4, 4, 4], a falling array and Example 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?