KatInterview

315. Count of Smaller Numbers After Self

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to compute, for each element nums[i], the number of elements to its right that are strictly smaller. A brute-force approach of iterating through the rest of the array for each element would result in an O(N²) time complexity, which is too slow given the constraint N <= 10^5.

Solution

Count of Smaller Numbers After Self in Python

class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        n = len(nums)
        if n == 0:
            return []

        # Create a list of tuples (value, original_index)
        items = [(nums[i], i) for i in range(n)]
        counts = [0] * n

        def merge_sort(items_slice):
            if len(items_slice) <= 1:
                return items_slice

            mid = len(items_slice) // 2
            left_half = merge_sort(items_slice[:mid])
            right_half = merge_sort(items_slice[mid:])
            
            return merge(left_half, right_half)

        def merge(left, right):
            merged = []
            i, j = 0, 0
            right_smaller_count = 0

            while i < len(left) and j < len(right):
                if left[i][0] <= right[j][0]:
                    # This element from the left half has `right_smaller_count` elements 
                    # from the right half that are smaller than it.
                    counts[left[i][1]] += right_smaller_count
                    merged.append(left[i])
                    i += 1
                else:
                    # The element from the right half is smaller.
                    right_smaller_count += 1
                    merged.append(right[j])
                    j += 1

            # Handle remaining elements in the left half
            while i < len(left):
                counts[left[i][1]] += right_smaller_count
                merged.append(left[i])
                i += 1
            
            # Handle remaining elements in the right half
            while j < len(right):
                merged.append(right[j])
                j += 1
            
            return merged

        merge_sort(items)
        return counts

Count of Smaller Numbers After Self in Java

class Solution {
    // Helper class to store value and original index
    private class Item {
        int val;
        int index;

        Item(int val, int index) {
            this.val = val;
            this.index = index;
        }
    }

    public List<Integer> countSmaller(int[] nums) {
        int n = nums.length;
        Item[] items = new Item[n];
        for (int i = 0; i < n; i++) {
            items[i] = new Item(nums[i], i);
        }

        int[] counts = new int[n];
        mergeSort(items, 0, n - 1, counts);

        List<Integer> result = new ArrayList<>(n);
        for (int count : counts) {
            result.add(count);
        }
        return result;
    }

    private void mergeSort(Item[] items, int low, int high, int[] counts) {
        if (low >= high) {
            return;
        }

        int mid = low + (high - low) / 2;
        mergeSort(items, low, mid, counts);
        mergeSort(items, mid + 1, high, counts);

        merge(items, low, mid, high, counts);
    }

    private void merge(Item[] items, int low, int mid, int high, int[] counts) {
        Item[] temp = new Item[high - low + 1];
        int i = low;      // pointer for left half
        int j = mid + 1;  // pointer for right half
        int k = 0;        // pointer for temp array
        int rightSmallerCount = 0;

        while (i <= mid && j <= high) {
            if (items[i].val <= items[j].val) {
                // This element from the left half has `rightSmallerCount` elements from the right half that are smaller than it.
                counts[items[i].index] += rightSmallerCount;
                temp[k++] = items[i++];
            } else {
                // The element from the right half is smaller.
                rightSmallerCount++;
                temp[k++] = items[j++];
            }
        }

        // Handle remaining elements in the left half
        while (i <= mid) {
            counts[items[i].index] += rightSmallerCount;
            temp[k++] = items[i++];
        }

        // Handle remaining elements in the right half
        while (j <= high) {
            temp[k++] = items[j++];
        }

        // Copy sorted and merged elements back to the original items array
        for (int m = 0; m < temp.length; m++) {
            items[low + m] = temp[m];
        }
    }
}

Count of Smaller Numbers After Self in C++

class Solution {
public:
    vector<int> countSmaller(vector<int>& nums) {
        int n = nums.size();
        if (n == 0) {
            return {};
        }
        
        // Create pairs of (value, original_index)
        vector<pair<int, int>> items(n);
        for (int i = 0; i < n; ++i) {
            items[i] = {nums[i], i};
        }
        
        vector<int> counts(n, 0);
        mergeSort(items, 0, n - 1, counts);
        
        return counts;
    }

private:
    void mergeSort(vector<pair<int, int>>& items, int low, int high, vector<int>& counts) {
        if (low >= high) {
            return;
        }
        
        int mid = low + (high - low) / 2;
        mergeSort(items, low, mid, counts);
        mergeSort(items, mid + 1, high, counts);
        
        merge(items, low, mid, high, counts);
    }
    
    void merge(vector<pair<int, int>>& items, int low, int mid, int high, vector<int>& counts) {
        vector<pair<int, int>> temp;
        temp.reserve(high - low + 1);

        int i = low;        // pointer for left half
        int j = mid + 1;    // pointer for right half
        int right_smaller_count = 0;

        while (i <= mid && j <= high) {
            if (items[i].first <= items[j].first) {
                // This element from the left half has `right_smaller_count` elements from the right half that are smaller than it.
                counts[items[i].second] += right_smaller_count;
                temp.push_back(items[i]);
                i++;
            } else {
                // The element from the right half is smaller.
                right_smaller_count++;
                temp.push_back(items[j]);
                j++;
            }
        }

        // Handle remaining elements in the left half
        while (i <= mid) {
            counts[items[i].second] += right_smaller_count;
            temp.push_back(items[i]);
            i++;
        }

        // Handle remaining elements in the right half
        while (j <= high) {
            temp.push_back(items[j]);
            j++;
        }

        // Copy sorted and merged elements back to the original items array
        for (int k = 0; k < temp.size(); ++k) {
            items[low + k] = temp[k];
        }
    }
};

Count of Smaller Numbers After Self in TypeScript

function countSmaller(nums: number[]): number[] {
    const n = nums.length;
    if (n === 0) {
        return [];
    }

    // Helper item structure to hold value and original index
    type Item = { val: number; index: number };

    const items: Item[] = nums.map((val, index) => ({ val, index }));
    const counts: number[] = new Array(n).fill(0);

    function mergeSort(low: number, high: number): void {
        if (low >= high) {
            return;
        }

        const mid = Math.floor((low + high) / 2);
        mergeSort(low, mid);
        mergeSort(mid + 1, high);
        merge(low, mid, high);
    }

    function merge(low: number, mid: number, high: number): void {
        const temp: Item[] = [];
        let i = low;      // Pointer for left half
        let j = mid + 1;  // Pointer for right half
        let rightSmallerCount = 0;

        while (i <= mid && j <= high) {
            if (items[i].val <= items[j].val) {
                // This element from the left half has `rightSmallerCount` elements
                // from the right half that are smaller than it.
                counts[items[i].index] += rightSmallerCount;
                temp.push(items[i]);
                i++;
            } else {
                // The element from the right half is smaller.
                rightSmallerCount++;
                temp.push(items[j]);
                j++;
            }
        }

        // Handle remaining elements in the left half
        while (i <= mid) {
            counts[items[i].index] += rightSmallerCount;
            temp.push(items[i]);
            i++;
        }

        // Handle remaining elements in the right half
        while (j <= high) {
            temp.push(items[j]);
            j++;
        }

        // Copy sorted and merged elements back to the original items array
        for (let k = 0; k < temp.length; k++) {
            items[low + k] = temp[k];
        }
    }

    mergeSort(0, n - 1);
    return counts;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.