Problem · Array

Count Smaller Prior Elements

Learn this problem
MediumTCTCSFULLTIMEOA

Problem statement

Given an integer array nums, return an array answer where answer[i] is the number of indices j < i for which nums[j] < nums[i].

Equal earlier values are not smaller and must not be counted.

Function

countSmallerBefore(nums: int[]) → int[]

Examples

Example 1

nums = [5,2,6,1,3]return = [0,0,2,0,2]

The counts are based only on earlier positions: 0, 0, 2, 0, and 2.

Example 2

nums = [2,2,2]return = [0,0,0]

Equal earlier values never count as smaller.

Constraints

  • 1 <= nums.length <= 200000
  • -10^9 <= nums[i] <= 10^9

More TCS problems

drafts saved locally
public int[] countSmallerBefore(int[] nums) {
    // Write your code here.
}
nums[5,2,6,1,3]
expected[0,0,2,0,2]
checking account