315. Count of Smaller Numbers After Self

You are given an integer array nums and you have to return a new counts array. The counts array has the property 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.

 

Constraints:

  • 0 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

Rust Solution

struct Solution;

use std::collections::BTreeMap;

impl Solution {
    fn count_smaller(nums: Vec<i32>) -> Vec<i32> {
        let mut count: BTreeMap<i32, usize> = BTreeMap::new();
        let n = nums.len();
        let mut res = vec![0; n];
        for i in (0..n).rev() {
            let mut sum = 0;
            let x = nums[i];
            for (_, v) in count.range(..x) {
                sum += v;
            }
            *count.entry(x).or_default() += 1;
            res[i] = sum as i32;
        }
        res
    }
}

#[test]
fn test() {
    let nums = vec![5, 2, 6, 1];
    let res = vec![2, 1, 1, 0];
    assert_eq!(Solution::count_smaller(nums), res);
}

Having problems with this solution? Click here to submit an issue on github.