easy How Many Numbers Are Smaller Than the Current Number
Problem Statement
Given an integer array nums, return the answer array where answer[i] is the count of smaller elements than nums[i].
Examples
-
Example 1:
- Input: nums =
[5, 3, 6, 1, 4] - Expected Output:
[3, 1, 4, 0, 2] - Justification: For the first element (5), there are three elements (3,1 and 4) that are smaller. For the second element (3), there is one element (1) smaller than it. For (6), there are four elements smaller than it. For (1), there are no smaller elements, and for (4), there are two elements (3 and 1) that are smaller.
- Input: nums =
-
Example 2:
- Input: nums =
[6, 6, 6, 6, 6] - Expected Output:
[0, 0, 0, 0, 0] - Justification: Each element is equal to the others, so there are no elements smaller than any given element.
- Input: nums =
-
Example 3:
- Input: nums =
[1, 2, 3, 4, 5] - Expected Output:
[0, 1, 2, 3, 4] - Justification: This is a strictly increasing sequence. Each number has all the previous numbers in the sequence smaller than itself.
- Input: nums =
Try it yourself
Try solving this question here:
✅ Solution How Many Numbers Are Smaller Than the Current Number
Problem Statement
Given an integer array nums, return the answer array where answer[i] is the count of smaller elements than nums[i].
Examples
-
Example 1:
- Input: nums =
[5, 3, 6, 1, 4] - Expected Output:
[3, 1, 4, 0, 2] - Justification: For the first element (5), there are three elements (3,1 and 4) that are smaller. For the second element (3), there is one element (1) smaller than it. For (6), there are four elements smaller than it. For (1), there are no smaller elements, and for (4), there are two elements (3 and 1) that are smaller.
- Input: nums =
-
Example 2:
- Input: nums =
[6, 6, 6, 6, 6] - Expected Output:
[0, 0, 0, 0, 0] - Justification: Each element is equal to the others, so there are no elements smaller than any given element.
- Input: nums =
-
Example 3:
- Input: nums =
[1, 2, 3, 4, 5] - Expected Output:
[0, 1, 2, 3, 4] - Justification: This is a strictly increasing sequence. Each number has all the previous numbers in the sequence smaller than itself.
- Input: nums =
Solution
To solve this problem, we can use a brute force approach by comparing each element with every other element to count how many numbers are smaller than it. However, a more efficient approach involves first sorting the array and using the sorted positions to determine how many elements are smaller. By sorting, we map each element to its position in the sorted order, which directly correlates to the number of elements smaller than it, considering duplicates.
This approach is effective because sorting gives us an ordered sequence where the position of each element naturally indicates the count of numbers less than it, except for handling duplicates. To handle duplicates effectively, we maintain a mapping of each unique number to its index in the sorted array. This ensures that each unique number gets the lowest possible rank, which corresponds to the count of numbers less than it.
Step-by-step Algorithm
-
Sort the Input Array: Create a sorted copy of the input array
nums. This sorted array will help us identify the relative position of each number, which indirectly tells us how many numbers are smaller than each element. -
Initialize an Empty HashMap (
index_map): This hashmap will store each unique number from the sorted array as keys, and their first occurrence index as values. This index represents the count of unique numbers that are smaller than the key number. -
Populate the HashMap: Iterate over the sorted array
sorted_nums. For each numbernuminsorted_nums, ifnumis not already a key inindex_map, addnumas a key with its indexias its value. Ifnumis already a key, skip to the next number. This step ensures each number is mapped to the number of unique elements that are smaller than it. -
Generate the Result Array: Iterate over the original array
nums, and for each elementnum, useindex_mapto find the count of numbers smaller thannum. Place this count in the corresponding position of a new result array. -
Return the Result Array: The result array, now filled with the counts of smaller numbers for each element in
nums, is returned as the final output.
Algorithm Walkthrough
-
Input Array:
[5, 3, 6, 1, 4] -
Step 1: Create a copy of the array and sort it.
- Sorted Array:
[1, 3, 4, 5, 6]
- Sorted Array:
-
Step 2: Initialize an empty hashmap
index_map. -
Step 3: Populate the hashmap.
- Iteration 1:
num = 1,index_mapbecomes{1: 0} - Iteration 2:
num = 3,index_mapbecomes{1: 0, 3: 1} - Iteration 3:
num = 4,index_mapbecomes{1: 0, 3: 1, 4: 2} - Iteration 4:
num = 5,index_mapbecomes{1: 0, 3: 1, 4: 2, 5: 3} - Iteration 5:
num = 6,index_mapbecomes{1: 0, 3: 1, 4: 2, 5: 3, 6: 4}
- Iteration 1:
-
Step 4: Generate the result array by iterating over the original array and using
index_map.- Original Array Element 5: 3 numbers are smaller (
index_map[5]), so first element in result array is3. - Original Array Element 3: 1 number is smaller (
index_map[3]), so second element in result array is1. - Original Array Element 6: 4 numbers are smaller (
index_map[6]), so third element in result array is4. - Original Array Element 1: 0 numbers are smaller (
index_map[1]), so fourth element in result array is0. - Original Array Element 4: 2 numbers are smaller (
index_map[4]), so fifth element in result array is2.
- Original Array Element 5: 3 numbers are smaller (
-
Step 5: The final result array is
[3, 1, 4, 0, 2], which is returned as the output.
Code
import java.util.Arrays;
import java.util.HashMap;
public class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] sortedNums = nums.clone();
Arrays.sort(sortedNums);
HashMap<Integer, Integer> indexMap = new HashMap<>();
// Map each number to its first occurrence index in the sorted array
for (int i = 0; i < sortedNums.length; i++) {
indexMap.putIfAbsent(sortedNums[i], i);
}
// Replace each element with its corresponding value from the map
int[] result = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
result[i] = indexMap.get(nums[i]);
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example 1
int[] example1 = solution.smallerNumbersThanCurrent(
new int[] { 5, 3, 6, 1, 4 }
);
System.out.println(Arrays.toString(example1)); // Expected: [3, 1, 4, 0, 2]
// Example 2
int[] example2 = solution.smallerNumbersThanCurrent(
new int[] { 6, 6, 6, 6, 6 }
);
System.out.println(Arrays.toString(example2)); // Expected: [0, 0, 0, 0, 0]
// Example 3
int[] example3 = solution.smallerNumbersThanCurrent(
new int[] { 1, 2, 3, 4, 5 }
);
System.out.println(Arrays.toString(example3)); // Expected: [0, 1, 2, 3, 4]
}
}
Complexity Analysis
Time Complexity
- Sorting: The initial sorting of the array takes
time, where (n) is the number of elements in the input array. - Mapping: Creating the map from the sorted array takes
time since we iterate through the sorted array once. - Building the Result Array: Iterating through the original array to form the result array, using the map for lookup, also takes
time.
Therefore, the overall time complexity of the algorithm is
Space Complexity
- Sorted Array: We create a sorted copy of the input array, which takes
space. - Mapping/Indexing Structure: The space taken by the map or dictionary is
in the worst case when all elements are unique. - Result Array: The output array also takes
space.
Thus, the total space complexity is
🤖 Don't fully get this? Learn it with Claude
Stuck on How Many Numbers Are Smaller Than the Current Number? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **How Many Numbers Are Smaller Than the Current Number** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **How Many Numbers Are Smaller Than the Current Number** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **How Many Numbers Are Smaller Than the Current Number**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **How Many Numbers Are Smaller Than the Current Number**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.