The Trapping Rainwater Problem involves calculating the total amount of water that can be trapped between non-negative integers in an elevation map, where each number represents the height of a bar. The naive approach iterates through every element to compute left and right maximums for each index, with a time complexity of O(n^2). A better solution uses prefix and suffix arrays to store the maximum heights on the left and right, reducing the time complexity to O(n) and requiring O(n) space.
The most efficient solution utilizes the two-pointer technique, achieving O(n) time and O(1) space. By comparing the maximum heights on the left and right, the algorithm decides whether to calculate water for the left or right pointer, updating the respective maximums and pointers accordingly. Alternate approaches, such as using a stack, offer O(n) time complexity but require O(n) space, leveraging next and previous greater elements to calculate trapped water efficiently.
For more details, please go through - Trapping Rain Water Problem – Tutorial with Illustrations