For each array element, count the smaller elements to its right

Quick Overview

For every position in an integer array of up to 100,000 elements, count how many later elements are strictly smaller. It tests per-index inversion counting in O(n log n) time and careful handling of equal values and original positions.

For each array element, count the smaller elements to its right

Company: Adobe

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Other

Given an integer array `nums`, return an array `counts` of the same length where `counts[i]` is the number of elements to the right of `nums[i]` that are smaller than `nums[i]`. ### Function Signature ```python def count_smaller(nums: list[int]) -> list[int]: ``` ### Rules - `counts[i]` is the number of indices `j > i` with `nums[j] < nums[i]`. - Smaller means strictly smaller. A later element equal to `nums[i]` does not count. - The array may contain duplicates and negative values. ### Constraints - `1 <= len(nums) <= 10^5` - `-10^4 <= nums[i] <= 10^4` ### Examples ```text Input: nums = [5, 2, 6, 1] Output: [2, 1, 1, 0] ``` To the right of 5 are 2, 6 and 1, and two of them (2 and 1) are smaller. To the right of 2 only 1 is smaller, to the right of 6 only 1 is smaller, and nothing follows 1. ```text Input: nums = [-1] Output: [0] ``` No elements follow -1. ```text Input: nums = [2, 0, 2, 1] Output: [2, 0, 1, 0] ``` The first 2 is followed by 0, 2 and 1. The equal 2 does not count, so its answer is 2. Nothing after the 0 is smaller, and the second 2 has only the 1 after it.

Overview: For every position in an integer array of up to 100,000 elements, count how many later elements are strictly smaller. It tests per-index inversion counting in O(n log n) time and careful handling of equal values and original positions.

Adobe logo
Adobe
Nov 24, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0

Given an integer array nums, return an array counts of the same length where counts[i] is the number of elements to the right of nums[i] that are smaller than nums[i].

Function Signature

def count_smaller(nums: list[int]) -> list[int]:

Rules

  • counts[i] is the number of indices j > i with nums[j] < nums[i] .
  • Smaller means strictly smaller. A later element equal to nums[i] does not count.
  • The array may contain duplicates and negative values.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4

Examples

Input: nums = [5, 2, 6, 1]
Output: [2, 1, 1, 0]

To the right of 5 are 2, 6 and 1, and two of them (2 and 1) are smaller. To the right of 2 only 1 is smaller, to the right of 6 only 1 is smaller, and nothing follows 1.

Input: nums = [-1]
Output: [0]

No elements follow -1.

Input: nums = [2, 0, 2, 1]
Output: [2, 0, 1, 0]

The first 2 is followed by 0, 2 and 1. The equal 2 does not count, so its answer is 2. Nothing after the 0 is smaller, and the second 2 has only the 1 after it.