n towers along a street from left to right, with heights given in heights; all heights are distinct.
Tower i can see tower j if i < j and every tower strictly between them is lower than both: min(heights[i], heights[j]) > max(heights[i+1..j-1]). Adjacent towers always see each other.
Return an array of length n whose entry i is the number of towers to the right that tower i can see.
Checking all pairs is O(n²); an O(n) solution exists.heights=[4, 2, 3, 1, 5] → [3, 1, 2, 1, 0]
Tower 0 sees towers 1, 2 and 4 (tower 3 is hidden by tower 2). Tower 1 sees only 2, tower 2 sees 3 and 4, tower 3 sees 4, and the last one sees nothing.
heights=[1, 2, 3] → [1, 1, 0]
Each tower sees only its neighbour, which is taller and blocks everything behind it.
heights=[4, 2, 3, 1, 5]
[3, 1, 2, 1, 0]
Run checks the first 3 tests in your browser. Submit checks all 99 tests on the server, hidden ones included.