Pour Water - Problem

You are given an elevation map represented as an integer array heights where heights[i] represents the height of the terrain at index i. The width at each index is 1.

You are also given two integers volume and k. volume units of water will fall at index k.

Water first drops at index k and rests on top of the highest terrain or water at that index. Then, it flows according to these rules:

  • If the droplet would eventually fall by moving left, then move left
  • Otherwise, if the droplet would eventually fall by moving right, then move right
  • Otherwise, rise to its current position

Here, "eventually fall" means that the droplet will eventually be at a lower level if it moves in that direction. Level means the height of terrain plus any water in that column.

Note: We assume there is infinitely high terrain on both sides out of bounds. Each unit of water must be in exactly one block.

Input & Output

Example 1 — Basic Water Flow
$ Input: heights = [2,1,1,2,1,2,2], volume = 4, k = 3
Output: [2,3,3,2,2,2,2]
💡 Note: Water drops at index 3 (height 2). First drop flows left to index 1 (height 1+1=2). Second drop flows left to index 2 (height 1+1=2). Third drop flows left to index 1 (height 2+1=3). Fourth drop flows left to index 2 (height 2+1=3).
Example 2 — Water Stays at Drop Position
$ Input: heights = [1,2,3,4], volume = 2, k = 2
Output: [1,2,5,4]
💡 Note: Water drops at index 2 (height 3). Both drops cannot flow left (heights increase) or right (height increases), so they stay at position 2: 3+2=5.
Example 3 — Water Flows Right
$ Input: heights = [3,1,3], volume = 5, k = 0
Output: [3,6,3]
💡 Note: Water drops at index 0 (height 3). Cannot flow left (out of bounds), but can flow right to index 1 (lower height). All 5 units flow right and settle at index 1: 1+5=6.

Constraints

  • 1 ≤ heights.length ≤ 100
  • 0 ≤ heights[i] ≤ 99
  • 0 ≤ volume ≤ 2000
  • 0 ≤ k < heights.length

Visualization

Tap to expand
Pour Water: Input → Flow → Final ResultInitial Terrain2112DROP k=3Water Flows Left2332🟤 Terrain 🔵 Water 🔴 Drop Positionvolume=4 drops flow to positions [1,1] creating heights [2,3,3,2]
Understanding the Visualization
1
Input
Terrain heights array, water volume, and drop position
2
Flow Simulation
Each water drop flows left first, then right, seeking lowest level
3
Final Heights
Original terrain heights plus accumulated water
Key Takeaway
🎯 Key Insight: Water simulation requires checking left flow first, then right flow, with each drop settling at the lowest reachable position
Asked in
Google 15 Facebook 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
580 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