#1365

How Many Numbers Are Smaller Than the Current Number

Easy Counting array

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

For every element, report how many other elements in the array are strictly smaller than it. Values are between 0 and 100.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: for each number, how many others are strictly smaller? Values are only 0..100, which is the hint for a faster way.

Why this works: count how often each value appears, then a running total of those counts tells you "how many values are below v" for every v at once.

Example: nums = [8, 1, 2, 2, 3]

counts:   1→1, 2→2, 3→1, 8→1below 1 = 0, below 2 = 1, below 3 = 3, below 8 = 4answer:  8→4, 1→0, 2→1, 2→1, 3→3   →  [4, 0, 1, 1, 3]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using the prefix count including v itself, which also counts equal elements. Use the total of values strictly less than v.