• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to secondary sidebar

GoHired

Interview Questions asked in Google, Microsoft, Amazon

Join WeekEnd Online Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

  • Home
  • Best Java Books
  • Algorithm
  • Internship
  • Certificates
  • About Us
  • Contact Us
  • Privacy Policy
  • Array
  • Stack
  • Queue
  • LinkedList
  • DP
  • Strings
  • Tree
  • Mathametical
  • Puzzles
  • Graph

Trapping Rain Water

May 25, 2017 by Dhaval Dave

Trapping Rain Water or Water collected between towers : Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.



Input - {1,5,2,3,1,7,2}
Output - 9

          |
          |
  | - - - |
  | - - - |
  | - | - |
  | | | - | |
| | | | | | |
1 5 2 3 1 7 2
Maximum water in above land can be 9 se - lines between buildings

Now Understand for below input

Input: arr[] = {3, 0, 0, 2, 0, 4}
Output: 10
Structure is like below
     |
|    |
|  | |
|__|_|
300204

Algorithm for Trapping Rain Water solution with O(N)

1. For each tower, we try to figure out if there is some unit of rainwater above it, if yes, then what is the amount.
2. Keep adding rainwater amount contribution by each tower to get total rainwater for given set of towers.

Points to Understand :

1. Try visualising the scenario. For rainwater to be on a tower, the height of tower should be less than (one of the tower on its left && one of the tower on its right).

Hence we arrive at our solution:
maxWaterOnCurrentTower = 0 , if there is no tower on left of current tower with more height Or there is no tower on right of current tower with more height else Min(MaxHeightLeft, MaxHeightRight) – currentHeight)

Joining above conditions:
maxWaterOnCurrentTower = Max(Min(MaxHeightLeft, MaxHeightRight) – currentHeight, 0);

Algorithm:
1: With given towerHeight array, create 2 arrays, maxSeenRight and maxSeenLeft.
maxLeft[i]  – max height on left side of Tower[i].
maxRight[i] – max height on right side of Tower[i].
2: Calculate for each tower:
rainwater = rainwater + Max(Min(maxLeft[i], maxRight[i]) – towerHeight[i], 0);

import java.util.*;
import java.lang.*;
import java.io.*;

class tappingWater {
 
 public static int maxwaterBetweenTowers(int[] arr, int n) {
         int[] left = new int[n]; 
         int[] right = new int[n]; 
         int collected = 0;
         right[n - 1] = arr[n - 1]; 
         for (int i = n - 2; i >= 0; i--) 
              right[i] = Math.max(arr[i], right[i + 1]);
         left[0] = arr[0]; 
         for (int i = 1; i<n; i++) left[i] = Math.max(left[i - 1], arr[i]);
         for (int i = 0; i<n; i++) collected += Math.min(left[i], right[i]) - arr[i];
 
         return collected;
   }
 } 
 public static void main(String[] args) {
 int[] towerHeight = { 1, 5, 2, 3, 1, 7, 2, 4 };
 //int[] towerHeight = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
 int n = towerHeight.length;
 System.out.println(maxwaterBetweenTowers(towerHeight,n));
 }
}

Similar Articles

Filed Under: Amazon Interview Question, Hacker Earth Questions, Interview Questions, Uncategorized Tagged With: Array

Reader Interactions

Primary Sidebar

Join WeekEnd Online/Offline Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

Join WeekEnd Online/Offline Batch from 4-April-2020

WhatsApp us

Secondary Sidebar

Custom Search

  • How I cracked AMAZON
  • LeetCode
  • Adobe
  • Amazon
  • Facebook
  • Microsoft
  • Hacker Earth
  • CSE Interview

Top Rated Questions

Rectangular chocolate bar Create at least one piece which consists of exactly nTiles tiles

LeetCode : Word Search

Print Power Set of a Set

Find two non repeating elements in an array of repeating elements

Puzzle : 100 doors in a row Visit and Toggle the door. What state the door will be after nth pass ?

Closed Parentheses checker

Given array of 0’s and 1’s. All 0’s are coming first followed by 1’s. find the position of first 1

How Radix sort works

Facebook Interview Question : Interleave List

Singly linked list

TicTacToe Game As Asked in Flipkart

Naurki.com Security Breach

Given a float number convert it into the string WITHOUT using any inbuilt Function

Regular Expression Matching

Find an index i such that Arr [i] = i in array of n distinct integers sorted in ascending order.

Walmart Labs Interview Experience

C Program for TAIL command of UNIX

The Magic HackerEarth Nirvana solutions Hiring Challenge

Adobe Interview Questions 8 month Exp

1014 Practice Question of New GRE – Princeton

Edit Distance ( Dynamic Programming )

Interfaces in C++ (Abstract Classes in C++)

Maximum size of square sub matrix with all 1’s in a binary matrix

Introduction To Number Theory ( Part 1 )

Sequence Finder Dynamic Programming

Longest Increasing Subsequence

Printing intermediate Integers between one element & next element of array

Add Sub Multiply very large number stored as string

N Petrol bunks or City arranged in circle. You have Fuel and distance between petrol bunks. Is it possible to find starting point so that we can travel all Petrol Bunks

Length of the longest substring without repeating characters

Copyright © 2025 · Genesis Framework · WordPress · Log in