Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Trapping Rain Water

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "42" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. Example 1: Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Example 2: Input: height = [4,2,0,3,2,5] Output: 9 Constraints: n == height.length 1 <= n <= 2 * 104 0 <= height[i] <= 105

Explanation

Here's the breakdown of the solution:

  • Key Idea: For each bar, the amount of water it can trap is determined by the minimum of the maximum height to its left and the maximum height to its right, minus the height of the bar itself.
  • Two-Pointer Approach: Efficiently find the maximum height to the left and right by traversing the array using two pointers, one from the left and one from the right. This avoids pre-calculation of left and right max heights for every element.
  • Simultaneous Traversal: The two pointers move towards each other. At each step, the pointer pointing to the smaller height is advanced, updating either the left max or right max as appropriate.

  • Runtime Complexity: O(n), Storage Complexity: O(1)

Code

    def trapping_rain_water(height):
    """
    Calculates the amount of rain water trapped between bars of different heights.

    Args:
        height: A list of non-negative integers representing the elevation map.

    Returns:
        The total amount of rain water trapped.
    """

    if not height:
        return 0

    left = 0
    right = len(height) - 1
    left_max = 0
    right_max = 0
    water = 0

    while left < right:
        if height[left] < height[right]:
            if height[left] >= left_max:
                left_max = height[left]
            else:
                water += left_max - height[left]
            left += 1
        else:
            if height[right] >= right_max:
                right_max = height[right]
            else:
                water += right_max - height[right]
            right -= 1

    return water

More from this blog

C

Chatmagic blog

2894 posts