
Problem
Solution
Submissions
Count of Smaller Numbers After Self
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C# program to implement the CountSmaller(int[] nums)
function, which counts for each element in the array how many elements to its right are smaller than it.
Example 1
- Input: nums = [5, 2, 6, 1]
- Output: [2, 1, 1, 0]
- Explanation:
- Step 1: Process each element from right to left.
- Step 2: For each element, count how many smaller elements exist to its right:
- For 5, there are 2 smaller elements to its right (2 and 1)
- For 2, there is 1 smaller element to its right (1)
- For 6, there is 1 smaller element to its right (1)
- For 1, there are 0 smaller elements to its right
- Step 3: Store these counts in an array.
- Step 4: Return the resulting array [2, 1, 1, 0].
Example 2
- Input: nums = [2, 0, 1, 0]
- Output: [2, 0, 1, 0]
- Explanation:
- Step 1: Process each element from right to left.
- Step 2: For each element, count how many smaller elements exist to its right:
- For 2, there are 2 smaller elements to its right (0 and 0)
- For 0, there are 0 smaller elements to its right (1 is larger)
- For 1, there is 1 smaller element to its right (0)
- For 0, there are 0 smaller elements to its right
- Step 3: Store these counts in an array.
- Step 4: Return the resulting array [2, 0, 1, 0].
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 input array
- Space Complexity: O(n) for storing the result and auxiliary data structures
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
- Consider using a Binary Search Tree (BST) to keep track of elements
- Merge sort with counting inversions can be adapted for this problem
- Binary Indexed Tree (BIT) or Segment Tree can efficiently solve this problem
- Process the array from right to left for optimal results