Count Of Smaller Numbers After Self

2 min read

Count of Smaller Numbers After Self: A Complete Guide

The count of smaller numbers after self is a classic algorithmic problem that asks you to determine, for each element in an array, how many elements to its right are strictly smaller. In practice, a brute-force approach is easy to write but far too slow for large inputs. This problem is frequently used in technical interviews and competitive programming because it tests your ability to optimize beyond naive solutions. Day to day, the efficient solutions rely on clever data structures and algorithmic paradigms such as merge sort, Fenwick trees, and segment trees. Formally, given an integer array nums, you must return an array counts where counts[i] is the number of indices j > i such that nums[j] < nums[i]. Understanding the count of smaller numbers after self deeply will strengthen your grasp of inversion counting, coordinate compression, and order-statistic operations Simple, but easy to overlook. Took long enough..

Real talk — this step gets skipped all the time.

Understanding the Problem

Let’s start with a concrete example. Suppose nums = [5, 2, 6, 1]. For each position:

  • At index 0, value 5: elements to the right are 2, 6, 1. Only 2 and 1 are smaller, so count = 2.
  • At index 1, value 2: elements to the right are 6, 1. Only 1 is smaller, so count = 1.
  • At index 2, value 6: element to the right is 1, which is smaller, so count = 1.
  • At index 3, value 1: no elements to the right, so count = 0.

The result is [2, 1, 1, 0]. But the problem becomes challenging when the array length reaches 100,000 or more. Here's the thing — a quadratic solution will time out, so we need an O(n log n) approach. The values can be negative, positive, or zero, and duplicates are allowed. The phrase “strictly smaller” means that equal values are not counted Turns out it matters..

Why the Brute Force Approach Falls Short

The most direct solution uses two nested loops:

for i from 0 to n-1:
    count = 0
    for j from i+1 to n-1:
        if nums[j] < nums[i]:
            count += 1
    result[i] = count

This approach is easy to understand and works correctly for small arrays. On the flip side, its time complexity is O(n²). Because of this, we must eliminate the inner loop by using a data structure that can answer “how many numbers smaller than X have I seen so far?So for an array of 100,000 elements, that is roughly 5 billion comparisons—far beyond the limits of typical online judges or interview time constraints. ” efficiently.

Real talk — this step gets skipped all the time.

New This Week

Just In

On a Similar Note

Keep the Momentum

Thank you for reading about Count Of Smaller Numbers After Self. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home