Tutorialspoint
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)
ArraysAlgorithmsTCS (Tata Consultancy Services)Capgemini
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

  • 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

Steps to solve by this approach:

 Step 1: Create arrays to track the counts and the original indices of elements.

 Step 2: Initialize the counts array to all zeros and the indices array with the original indices (0 to n-1).
 Step 3: Implement a merge sort algorithm to sort the array.
 Step 4: During the merge step, when choosing an element from the right subarray, increment a counter.
 Step 5: When choosing an element from the left subarray, add the current counter to its count of smaller elements on the right.
 Step 6: After sorting, the counts array will contain the number of smaller elements to the right of each element in the original array.
 Step 7: Convert the counts array to a List and return it as the result.

Submitted Code :