Show problems as
Classic problem #315HardArrayBinary SearchDivide and ConquerBinary Indexed TreeSegment TreeMerge SortOrdered SetTreap

Count of Smaller Numbers After Self

Real-world version: Cooler Gauges Downstream
Tracked in this browser only
Read Count of Smaller Numbers After Self on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstPrefix Sums · Arrays, animated step by step

Temperature gauges are fixed along a cooling pipe in the order the coolant flows through them. readings[i] is the temperature in degrees at the gauge in position i, and a gauge lies downstream of another when its position is larger.

For each gauge, an engineer wants to know how many of the gauges downstream of it read strictly cooler than it does. A gauge reading exactly the same temperature does not count, and gauges upstream are ignored.

Return an array cooler of the same length as readings, where cooler[i] is that count for the gauge in position i.

Examples

Example 1

Input
readings = [9, 4, 12, 2]
Output
[2, 1, 1, 0]

Downstream of the 9 sit 4, 12 and 2, of which 4 and 2 are cooler, giving 2. Downstream of the 4 sit 12 and 2, of which only 2 is cooler, giving 1. Downstream of the 12 sits 2 alone, giving 1, and the last gauge has nothing downstream, giving 0.

Example 2

Input
readings = [6, 6, 6, 6]
Output
[0, 0, 0, 0]

Every gauge reads the same temperature, and an equal reading is not cooler, so no gauge counts any of the ones downstream of it.

Example 3

Input
readings = [-5, -9, -5, -20, 0]
Output
[2, 1, 1, 0, 0]

The first gauge reads -5 and finds -9 and -20 cooler downstream, giving 2, while the -5 in the middle finds only -20, giving 1. The gauge reading -20 has just the 0 downstream, which is warmer, so its count is 0.

Constraints

  • 1 <= readings.length <= 10^5
  • -10^4 <= readings[i] <= 10^4

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def cooler_downstream(readings: list[int]) -> list[int]:
Java
public List<Integer> coolerDownstream(int[] readings)