Tutorialspoint
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
AlgorithmsTreeTutorialspointHCL Technologies
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create a modified merge sort algorithm that keeps track of indexes.
 Step 2: Initialize an array to store the count of smaller elements for each number.
 Step 3: Process the array using merge sort, maintaining the original indices.
 Step 4: During the merge operation, when we take an element from the left subarray, increment its count by the number of elements already taken from the right subarray.
 Step 5: Return the array of counts matching the original order of the input array.

Submitted Code :