Pour Water

You are given an array of heights that represents the terrain and are required to pour a specific volume of water at a certain index ( k ). The water follows specific rules to move to the left, right, or stay in place.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
    def pourWater(self, heights: List[int], volume: int, k: int) -> List[int]:
        # Iterate for the given volume of water
        for _ in range(volume):
            pos = k # Initialize the position of the droplet

            # Move left if possible
            for i in range(k - 1, -1, -1):
                if heights[i] < heights[i + 1]:
                    pos = i
                elif heights[i] > heights[i + 1]:
                    break

            # If the droplet doesn't move left, then try moving right
            if pos == k:
                for i in range(k + 1, len(heights)):
                    if heights[i] < heights[i - 1]:
                        pos = i
                    elif heights[i] > heights[i - 1]:
                        break

            # Increment the height at the droplet's position
            heights[pos] += 1
            
        return heights

Here’s how the code works:

  1. For each droplet (iterated by the given volume), try to move it to the left by checking the conditions.
  2. If the droplet doesn’t move left, then try moving it to the right.
  3. Increment the height at the final position of the droplet.

This code follows the given constraints and requirements, and the time complexity of this solution is ( O(\text{volume} \times \text{heights.length}) ).