Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].
Example 1:
Input: nums = [5,2,6,1] Output: [2,1,1,0] Explanation: To the right of 5 there are 2 smaller elements (2 and 1). To the right of 2 there is only 1 smaller element (1). To the right of 6 there is 1 smaller element (1). To the right of 1 there is 0 smaller element.
Example 2:
Input: nums = [-1] Output: [0]
Example 3:
Input: nums = [-1,-1] Output: [0,0]
Constraints:
1 <= nums.length <= 105-104 <= nums[i] <= 104Problem summary: Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Segment Tree
[5,2,6,1]
[-1]
[-1,-1]
count-of-range-sum)queue-reconstruction-by-height)reverse-pairs)how-many-numbers-are-smaller-than-the-current-number)count-good-triplets-in-an-array)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #315: Count of Smaller Numbers After Self
class Solution {
public List<Integer> countSmaller(int[] nums) {
Set<Integer> s = new HashSet<>();
for (int v : nums) {
s.add(v);
}
List<Integer> alls = new ArrayList<>(s);
alls.sort(Comparator.comparingInt(a -> a));
int n = alls.size();
Map<Integer, Integer> m = new HashMap<>(n);
for (int i = 0; i < n; ++i) {
m.put(alls.get(i), i + 1);
}
BinaryIndexedTree tree = new BinaryIndexedTree(n);
LinkedList<Integer> ans = new LinkedList<>();
for (int i = nums.length - 1; i >= 0; --i) {
int x = m.get(nums[i]);
tree.update(x, 1);
ans.addFirst(tree.query(x - 1));
}
return ans;
}
}
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
}
public void update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += lowbit(x);
}
}
public int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= lowbit(x);
}
return s;
}
public static int lowbit(int x) {
return x & -x;
}
}
// Accepted solution for LeetCode #315: Count of Smaller Numbers After Self
type BinaryIndexedTree struct {
n int
c []int
}
func newBinaryIndexedTree(n int) *BinaryIndexedTree {
c := make([]int, n+1)
return &BinaryIndexedTree{n, c}
}
func (this *BinaryIndexedTree) lowbit(x int) int {
return x & -x
}
func (this *BinaryIndexedTree) update(x, delta int) {
for x <= this.n {
this.c[x] += delta
x += this.lowbit(x)
}
}
func (this *BinaryIndexedTree) query(x int) int {
s := 0
for x > 0 {
s += this.c[x]
x -= this.lowbit(x)
}
return s
}
func countSmaller(nums []int) []int {
s := make(map[int]bool)
for _, v := range nums {
s[v] = true
}
var alls []int
for v := range s {
alls = append(alls, v)
}
sort.Ints(alls)
m := make(map[int]int)
for i, v := range alls {
m[v] = i + 1
}
ans := make([]int, len(nums))
tree := newBinaryIndexedTree(len(alls))
for i := len(nums) - 1; i >= 0; i-- {
x := m[nums[i]]
tree.update(x, 1)
ans[i] = tree.query(x - 1)
}
return ans
}
# Accepted solution for LeetCode #315: Count of Smaller Numbers After Self
class BinaryIndexedTree:
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
@staticmethod
def lowbit(x):
return x & -x
def update(self, x, delta):
while x <= self.n:
self.c[x] += delta
x += BinaryIndexedTree.lowbit(x)
def query(self, x):
s = 0
while x > 0:
s += self.c[x]
x -= BinaryIndexedTree.lowbit(x)
return s
class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
alls = sorted(set(nums))
m = {v: i for i, v in enumerate(alls, 1)}
tree = BinaryIndexedTree(len(m))
ans = []
for v in nums[::-1]:
x = m[v]
tree.update(x, 1)
ans.append(tree.query(x - 1))
return ans[::-1]
// Accepted solution for LeetCode #315: Count of Smaller Numbers After Self
struct Solution;
use std::collections::BTreeMap;
impl Solution {
fn count_smaller(nums: Vec<i32>) -> Vec<i32> {
let mut count: BTreeMap<i32, usize> = BTreeMap::new();
let n = nums.len();
let mut res = vec![0; n];
for i in (0..n).rev() {
let mut sum = 0;
let x = nums[i];
for (_, v) in count.range(..x) {
sum += v;
}
*count.entry(x).or_default() += 1;
res[i] = sum as i32;
}
res
}
}
#[test]
fn test() {
let nums = vec![5, 2, 6, 1];
let res = vec![2, 1, 1, 0];
assert_eq!(Solution::count_smaller(nums), res);
}
// Accepted solution for LeetCode #315: Count of Smaller Numbers After Self
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #315: Count of Smaller Numbers After Self
// class Solution {
// public List<Integer> countSmaller(int[] nums) {
// Set<Integer> s = new HashSet<>();
// for (int v : nums) {
// s.add(v);
// }
// List<Integer> alls = new ArrayList<>(s);
// alls.sort(Comparator.comparingInt(a -> a));
// int n = alls.size();
// Map<Integer, Integer> m = new HashMap<>(n);
// for (int i = 0; i < n; ++i) {
// m.put(alls.get(i), i + 1);
// }
// BinaryIndexedTree tree = new BinaryIndexedTree(n);
// LinkedList<Integer> ans = new LinkedList<>();
// for (int i = nums.length - 1; i >= 0; --i) {
// int x = m.get(nums[i]);
// tree.update(x, 1);
// ans.addFirst(tree.query(x - 1));
// }
// return ans;
// }
// }
//
// class BinaryIndexedTree {
// private int n;
// private int[] c;
//
// public BinaryIndexedTree(int n) {
// this.n = n;
// c = new int[n + 1];
// }
//
// public void update(int x, int delta) {
// while (x <= n) {
// c[x] += delta;
// x += lowbit(x);
// }
// }
//
// public int query(int x) {
// int s = 0;
// while (x > 0) {
// s += c[x];
// x -= lowbit(x);
// }
// return s;
// }
//
// public static int lowbit(int x) {
// return x & -x;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.