AlgoMaster Logo

Count of Smaller Numbers After Self

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The simplest approach is to check each element and count how many numbers after it are smaller. This involves iterating over each element and then iterating over subsequent elements to count the smaller numbers.

Code:

2. Binary Search Tree (BST)

Intuition:

By using a BST, where each node contains the number of times it and all its left descendants have been inserted, we can efficiently insert each number in reverse order and count how many smaller elements have already been inserted.

Code:

3. Fenwick Tree (or Binary Indexed Tree)

Intuition:

Fenwick Tree is useful for maintaining prefix sums efficiently. We can translate the problem into finding the frequency of numbers, querying this frequency with a Fenwick Tree while iterating the array backwards.

Code:

4. Merge Sort

Intuition:

This is a modification of merge sort. What we can do is keep track of how many elements are moved after an item in the merge process.

Code: