Algo-Sim › Advanced Data Structures

Count of Smaller Numbers After Self

Hard · Advanced Data Structures · step through it in Java, Python and C++ on your own input

For each element, how many later elements are smaller? Scan from the right with a Fenwick tree over value ranks, or credit each index during merge sort.

Problem

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

Constraints

Edge cases to test

Follow-up questions

Why compress the values to ranks?
A Fenwick tree needs small indices; mapping values to 1..m keeps it O(n log n) for any value range.
What is the merge-sort approach?
While merging, a left element gains the number of right elements already placed before it: O(n log n).

Solution

Java

public List<Integer> countSmaller(int[] nums) {
    // Compress values to ranks 1..m so the tree has one slot per distinct value.
    int[] sorted = Arrays.stream(nums).distinct().sorted().toArray();
    int m = sorted.length;
    int[] tree = new int[m + 1];
    Integer[] out = new Integer[nums.length];
    for (int i = nums.length - 1; i >= 0; i--) {
        int rank = Arrays.binarySearch(sorted, nums[i]) + 1;
        int count = 0;
        // How many values already seen (all to the right) have a smaller rank?
        for (int j = rank - 1; j > 0; j -= j & -j) count += tree[j];
        out[i] = count;
        for (int j = rank; j <= m; j += j & -j) tree[j]++;
    }
    return Arrays.asList(out);
}

Python

from bisect import bisect_left


def count_smaller(nums):
    # Compress values to ranks 1..m so the tree has one slot per distinct value.
    ranks = sorted(set(nums))
    tree = [0] * (len(ranks) + 1)
    out = [0] * len(nums)
    for i in range(len(nums) - 1, -1, -1):
        rank = bisect_left(ranks, nums[i]) + 1
        # How many values already seen (all to the right) have a smaller rank?
        j, count = rank - 1, 0
        while j > 0:
            count += tree[j]
            j -= j & -j
        out[i] = count
        j = rank
        while j < len(tree):
            tree[j] += 1
            j += j & -j
    return out

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> countSmaller(vector<int> &nums) {
        // Compress values to ranks 1..m so the tree has one slot per distinct value.
        vector<int> sorted(nums);
        sort(sorted.begin(), sorted.end());
        sorted.erase(unique(sorted.begin(), sorted.end()), sorted.end());
        int m = sorted.size(), n = nums.size();
        vector<int> tree(m + 1), out(n);
        for (int i = n - 1; i >= 0; i--) {
            int rank = lower_bound(sorted.begin(), sorted.end(), nums[i]) - sorted.begin() + 1;
            int count = 0;
            // How many values already seen (all to the right) have a smaller rank?
            for (int j = rank - 1; j > 0; j -= j & -j) count += tree[j];
            out[i] = count;
            for (int j = rank; j <= m; j += j & -j) tree[j]++;
        }
        return out;
    }
};

More Advanced Data Structures problems