Building Shadow Calculator - Problem

You are given an array of integers representing the heights of buildings in a row. The buildings are illuminated by a light source positioned to the left of all buildings, casting shadows to the right.

Each building casts a shadow with length equal to its height. However, if a building is blocked by a taller building to its left, it won't cast any shadow (the taller building's shadow covers it completely).

Calculate the total length of all visible shadows cast to the right.

Example: For buildings [3, 1, 4, 1, 5], only buildings with heights 3, 4, and 5 cast shadows (heights 3→4→5 are increasing from left). The two buildings with height 1 are blocked. Total shadow length = 3 + 4 + 5 = 12.

Input & Output

Example 1 — Basic Case
$ Input: heights = [3,1,4,1,5]
Output: 12
💡 Note: Building 3 casts shadow (no taller building to left). Building 1 is blocked by 3. Building 4 casts shadow (4 > 3). Building 1 is blocked by 4. Building 5 casts shadow (5 > 4). Total: 3 + 4 + 5 = 12
Example 2 — All Increasing
$ Input: heights = [1,2,3,4,5]
Output: 15
💡 Note: Each building is taller than all previous ones, so all cast shadows: 1 + 2 + 3 + 4 + 5 = 15
Example 3 — All Decreasing
$ Input: heights = [5,4,3,2,1]
Output: 5
💡 Note: Only the first building (height 5) casts a shadow. All others are blocked by it. Total: 5

Constraints

  • 1 ≤ heights.length ≤ 104
  • 1 ≤ heights[i] ≤ 109

Visualization

Tap to expand
INPUTALGORITHMRESULT31415Buildings: [3,1,4,1,5]1Track max height = 023 > 0: add 3, max = 331 ≤ 3: skip (blocked)44 > 3: add 4, max = 455 > 4: add 5, max = 5Only heights > max cast shadowsTotal Shadow123 + 4 + 5 = 12Buildings 3, 4, 5 castvisible shadowsKey Insight:Only buildings taller than all previous buildings can cast shadows - track maximum height seen so far!TutorialsPoint - Building Shadow Calculator | Optimized Single Pass
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen