Skip to the solution
HardDSA13 min read

Count of smaller numbers after self with Fenwick tree — how to coordinate compress?

855 views

The problem

Question presented to candidate: "Given an integer array, return an array where counts[i] is the number of elements to the right of index i that are strictly smaller than nums[i]. Values can be negative and as large as a billion, and the array can have 100,000 elements. Solve it in Python with a Fenwick tree — and explain how you deal with the value range."

What a strong answer should cover:

  • The O(n²) brute force first, and why n = 10^5 needs O(n log n).
  • The right-to-left scan: the answer for i is a prefix count of values already seen, then add nums[i].
  • How a Fenwick tree does point add and prefix sum in O(log n) with i & -i, and why it is 1-indexed.
  • Coordinate compression: sorted distinct values, 1-based ranks, equal values sharing a rank, and prefix(rank − 1) for strictly smaller.
  • Alternatives: merge sort counting, a segment tree, a BST with subtree sizes.
  • Python details: sorted(set(nums)) and a dict comprehension for ranks (or bisect.bisect_left), a list of size m + 1, and no overflow concerns for totals.

Clarifying questions expected:

  • What is the value range — can values be negative or very large?
  • Do equal values count as smaller?
  • How large can n be?

Code / implementation expected: Yes — compression plus a Fenwick tree in Python, O(n log n) time and O(n) space.

  • fenwick
  • binary indexed
  • Amazon

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read · 15 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonCoordinate compression + Fenwick tree on eight inputs
PythonFenwick trace on [5, 2, 6, 1], brute force vs Fenwick on 3,000 values

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 136 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

How does the Bellman-Ford algorithm work?

Continue