Tutorialspoint
Problem
Solution
Submissions

Smaller Numbers After Self

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program that takes an array of integers and returns an array where each element represents the count of smaller numbers to the right of the current element. For each element in the input array, count 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: For 5, elements to right are [2, 6, 1]. Smaller than 5: [2, 1] → count = 2
     Step 2: For 2, elements to right are [6, 1]. Smaller than 2: [1] → count = 1
     Step 3: For 6, elements to right are [1]. Smaller than 6: [1] → count = 1
     Step 4: For 1, no elements to right → count = 0
Example 2
  • Input: nums = [1, 2, 3, 4]
  • Output: [0, 0, 0, 0]
  • Explanation:
     Step 1: For 1, elements to right are [2, 3, 4]. None smaller than 1 → count = 0
     Step 2: For 2, elements to right are [3, 4]. None smaller than 2 → count = 0
     Step 3: For 3, elements to right are [4]. None smaller than 3 → count = 0
     Step 4: For 4, no elements to right → count = 0
Constraints
  • 1 ≤ nums.length ≤ 10^5
  • -10^4 ≤ nums[i] ≤ 10^4
  • Return an array of the same length as input
  • Time Complexity: O(n log n)
  • Space Complexity: O(n)
ArraysAlgorithmsTutorialspointWalmart
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

  • Use merge sort with index tracking to count inversions efficiently
  • Create an array of indices and sort based on values while tracking original positions
  • During merge process, count how many elements from right array are smaller
  • Maintain original indices to place counts in correct positions
  • Use the divide and conquer approach of merge sort for efficient counting
  • Build result array using the inversion counts calculated during merge

Steps to solve by this approach:

 Step 1: Create an Element structure to store both value and original index
 Step 2: Initialize result array with zeros and create element array from input
 Step 3: Use merge sort approach but instead of sorting values, track inversions
 Step 4: During merge process, when element from left is greater than right, count inversions
 Step 5: Add the count of smaller elements to the result array at original index
 Step 6: Recursively apply merge sort to divide the problem into smaller subproblems
 Step 7: Combine results from both halves while maintaining the inversion count

Submitted Code :