Pour Water - Problem

Imagine you're standing on a mountainous terrain with an elevation map represented as an integer array heights, where heights[i] represents the height at position i. Each position has a width of 1 unit.

You have volume units of water that will be poured at position k. Each water droplet follows realistic physics:

  • ๐ŸŒŠ Water flows left first: If moving left would eventually lead to a lower level, the water flows left
  • ๐ŸŒŠ Otherwise flows right: If left doesn't work but right leads to lower ground, water flows right
  • ๐ŸŒŠ Otherwise stays put: If neither direction leads downhill, water accumulates at the current position

The terrain extends infinitely high on both sides, so water can't escape the boundaries. Your task is to simulate the water flow and return the final state of the terrain with accumulated water.

Note: Water cannot be split - each unit must occupy exactly one position at its final resting place.

Input & Output

example_1.py โ€” Basic Water Flow
$ Input: heights = [2,1,1,2,1,2,2], volume = 4, k = 3
โ€บ Output: [2,2,2,3,1,2,2]
๐Ÿ’ก Note: Water starts at index 3. First droplet flows left to index 1 (lowest point). Second droplet flows left to index 2. Third droplet flows left but both positions are filled, so stays at index 3. Fourth droplet also stays at index 3.
example_2.py โ€” Right Flow
$ Input: heights = [1,2,3,4], volume = 2, k = 2
โ€บ Output: [3,2,3,4]
๐Ÿ’ก Note: Water at index 2 cannot flow left (uphill), cannot flow right (uphill), so it accumulates at the starting position k=2.
example_3.py โ€” Mixed Flow
$ Input: heights = [3,1,3], volume = 5, k = 1
โ€บ Output: [3,6,3]
๐Ÿ’ก Note: Position 1 is surrounded by higher terrain, so all water accumulates there forming a deep pool.

Constraints

  • 1 โ‰ค heights.length โ‰ค 100
  • 0 โ‰ค heights[i] โ‰ค 99
  • 0 โ‰ค volume โ‰ค 2000
  • 0 โ‰ค k < heights.length
  • Water cannot be split between positions

Visualization

Tap to expand
๐Ÿ’งWater flows left to find the lowest available position
Understanding the Visualization
1
Initial State
Terrain with varying heights, water ready to drop at position k
2
Left Search
Water checks left direction for lowest reachable position
3
Right Search
If left doesn't work, check right direction
4
Settlement
Water settles at chosen position, increasing height
5
Repeat
Process continues for all remaining water units
Key Takeaway
๐ŸŽฏ Key Insight: Water simulation requires checking left first (preferred direction), then right, mimicking real physics where water seeks the lowest available position.
Asked in
Google 32 Facebook 28 Amazon 24 Apple 18
28.4K Views
Medium Frequency
~25 min Avg. Time
986 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