Skip to content

315. Count of Smaller Numbers After Self

Description

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:
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.

Example 2:

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

Example 3:

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

 

Constraints:

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104

 

Solutions

Solution: Binary Indexed Tree

  • Time complexity: O(nlogn)
  • Space complexity: O(n)

 

JavaScript

js
/**
 * @param {number[]} nums
 * @return {number[]}
 */
const countSmaller = function (nums) {
  const n = nums.length;
  const max = Math.max(...nums);
  const min = Math.min(...nums);
  const BIT = new Array(max - min + 2).fill(0);
  const result = new Array(n);
  const updateBIT = num => {
    while (num < BIT.length) {
      BIT[num] += 1;
      num += num & -num;
    }
  };
  const searchBIT = num => {
    let count = 0;

    while (num > 0) {
      count += BIT[num];
      num -= num & -num;
    }
    return count;
  };

  for (let index = n - 1; index >= 0; index--) {
    const num = nums[index] - min + 1;

    result[index] = searchBIT(num);
    updateBIT(num + 1);
  }
  return result;
};

Released under the MIT license