
Problem
Solution
Submissions
Smaller Numbers After Self
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
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:
For nums[0] = 5, there are two elements (2 and 1) to the right that are smaller.
For nums[1] = 2, there is one element (1) to the right that is smaller.
For nums[2] = 6, there is one element (1) to the right that is smaller.
For nums[3] = 1, there are no elements to the right that are smaller.
Example 2
- Input: nums = [2, 0, 1]
- Output: [2, 0, 0]
- Explanation:
For nums[0] = 2, there are two elements (0 and 1) to the right that are smaller.
For nums[1] = 0, there are no elements to the right that are smaller.
For nums[2] = 1, there are no elements to the right that are smaller.
Constraints
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
- Time Complexity: O(n log n), where n is the length of the array
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- This problem can be solved using a modified merge sort algorithm with a count array
- The key insight is that during the merge step of merge sort, we can count how many elements are smaller on the right
- For each element, we need to keep track of its original position before sorting
- Use a pair class to store the value and its original index
- During the merge step, when an element from the right half is chosen, increment the count of smaller elements for all the remaining elements in the left half