← Questions

Count of smaller numbers after self

0
AmazonCodingLast asked Jul 2025

A coding interview question asked in Amazon's technical phone screen, last asked Jul 2025. It tests merge sort, fenwick tree and arrays.

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

Interface

Unless you agree on a different interface with the interviewer, assume:

  • count_smaller(nums: list[int]) -> list[int] — returns a list of the same length.

Example

[5, 2, 6, 1]   ->  [2, 1, 1, 0]
[3, 1, 2, 1]   ->  [3, 0, 1, 0]   # equal values do not count
[-1, -1]       ->  [0, 0]

Constraints

  • 0 <= len(nums) <= 200,000
  • -10^9 <= nums[i] <= 10^9
  • Aim for O(n log n) time.

Clarifying questions

  • Strictly smaller, or smaller or equal?
  • Can values be negative or repeat?
  • Is O(n) extra space acceptable?

What a strong answer covers

  • The O(n^2) double loop and why it is too slow at this size.
  • A Fenwick tree over compressed values: walk from the right, query the count of values below nums[i], then add nums[i]. O(n log n) time, O(n) space.
  • The merge-sort alternative: sort (value, index) pairs and, while merging, add to each left element the number of right-half elements already placed before it.
  • Handling equal values correctly in both approaches; tests: empty, all equal, sorted ascending and descending.

Follow-ups

  • Count the elements to the right that are larger, or within a value range [lo, hi].
  • Count the total number of inversions in the array.
  • The array is a stream and queries arrive online: how many earlier elements are smaller than the new one?

Where it's asked

  • Amazon · Technical phone screen · Last asked Jul 202560 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI

What it tests

merge sort · fenwick tree · arrays

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding