Leetcode!
  • LeetCode!
  • My personal guide to Leetcode
  • Array
    • 11. Container With Most Water
    • 15. 3Sum
    • 219. Contains Duplicate II
    • 238. Product of Array Except Self
    • 245. Shortest Word Distance III
    • 392. Is Subsequence
    • 442. Find All Duplicates in an Array
    • 561. Array Partition I
    • 661. Image Smoother
    • 697. Degree of an Array
    • 723. Candy Crush
    • 832. Flipping an Image
  • Backtracking
    • 294. Flip Game II
    • 401. Binary Watch
    • 1079. Letter Tile Possibilities
  • Binary Search
    • 744. Find Smallest Letter Greater Than Target
    • 852. Peak Index in a Mountain Array
  • String
    • 6. ZigZag Conversion
    • 17. Letter Combinations of a Phone Number
    • 38. Count and Say
    • 521. Longest Uncommon Subsequence I
    • 544. Output Contest Matches
    • 937. Reorder Data in Log Files
  • Design
    • 251. Flatten 2D Vector
    • 281. Zigzag Iterator
  • Hash Table
    • 1. Two Sum
    • 508. Most Frequent Subtree Sum
    • 884. Uncommon Words from Two Sentences
    • 734. Sentence Similarity
  • Linked List
    • 2. Add Two Numbers
  • Unsorted
    • 917. Reverse Only Letters
  • Math
    • 43. Multiply Strings
    • 462. Minimum Moves to Equal Array Elements II
    • 553. Optimal Division
    • 800. Similar RGB Color
  • Greedy
    • 406. Queue Reconstruction by Height
    • 861. Score After Flipping Matrix
  • Tree
    • 701. Insert into a Binary Search Tree
    • 897. Increasing Order Search Tree
  • Divide and Conquer
    • 53. Maximum Subarray
  • Dynamic Programming
    • 62. Unique Paths
    • 63. Unique Paths II
    • 64. Minimum Path Sum
    • 120. Triangle
    • 198. House Robber
    • 213. House Robber II
    • 303. Range Sum Query - Immutable
    • 518. Coin Change 2
    • 750. Number Of Corner Rectangles
    • 337. House Robber III
  • Depth first search
    • 841. Keys and Rooms
  • Trie
    • 677. Map Sum Pairs
  • Two pointer
    • 42. Trapping Rain Water
Powered by GitBook
On this page
  • Approach 1: Brute Force
  • Approach 2: Memoise max
  1. Two pointer

42. Trapping Rain Water

Approach 1: Brute Force

class Solution:
    def trap(self, heights):
        """
        :type height: List[int]
        :rtype: int
        """
        ans = 0
        max_left, max_right = 0,0
        for index, height in enumerate(heights):
            ans += min(max(heights[:index+1]), max(heights[index:])) - height
        return ans

For each index, search for the maximum height to its left (max_left) and the maximum height of its right (max_right). For each index, the water it can hold is the minimum of the two max's minus the current level. This way you can get the total amount of water that can be held!

Time Complexity: O(N^2), where N is the length of the array

Space Complexity: O(1)

Approach 2: Memoise max

class Solution:
    def trap(self, heights):
        """
        :type height: List[int]
        :rtype: int
        """
        if len(heights) == 0:
            return 0
        ans = 0
        l, r = 0, len(heights) - 1
        ma_l, ma_r = heights[l], heights[r]
        while l < r:
            ma_l, ma_r = max(heights[l], ma_l), max(heights[r], ma_r)
            if ma_l <= ma_r:
                ans += ma_l - heights[l]
                l += 1
            else:
                ans += ma_r - heights[r]
                r -= 1
        return ans

Instead of recalculating the max's at each index we can memoise the two by storing the left max and the right max and only updating them when required. This way it reduces the time it takes for us to compute the max height to the left and to the right!

Time Complexity: O(N^2), where N is the length of the array

Space Complexity: O(1)

Previous677. Map Sum Pairs

Last updated 5 years ago