AirBnB | Onsite | Similar to trapping rain water | Found it too hard :(
Anonymous User
2236

I'm sure everyone remembers the classic Trapping Rain Water (https://leetcode.com/problems/trapping-rain-water/)

Well here is an interesting twist.

Let's say you have been given a set of heights representing the heights of buildings. Additionally, you have been given an index (let's call it target) and a quantity of water (let's call it q).

In this question, you will be asked to print on the screen the state of the world if q quantities of water is poured at index target.

For example.

If building array is [5, 2, 0 , 3, 4], we represent it as:

O
O       O
O     O O
O O   O O
O O   O O

Now if q = 1, and target = 2, then you are supposed to print:

O 
O       O
O     O O
O O   O O
O O W O O

W represents water, O represents the building.

This was my second question in a 45 min interview. Question has a lots of edge cases. I could think of these:

  • What happens if you pour water at a peak? Does it go left or right? Or split equally into two.
    Interviewer asked me to pick any option. Selected that it goes all on the right side
  • What happens if you pour water at the edge?
    Discussed that it would flow out
  • What happens when a plain or a plateau is formed?

Overall, I wrote code of a recursive approach. My approach was

  • Step 1 : Check if there is a slope on the right. If it exists, go down to the slope until you reach a valley.
  • Step 2 : If there is no slope on the right, check if one exists on the left.
  • Step 3 : In either step 1 or 2 if you reach the ends, it means that the water will spill away.
  • Step 4 : Once you reach a valley, find the next high peaks on left and right. Minimum of the two is amount of water we can add at target index.
  • Step 5 : Once added, traverse to the left until the height on the left is equal to current height after pouring water.
  • Step 6 : Recursively call this method starting the process at step 1 because now other parts of the area can be filled with water.

Obviously if no water remains, we exit.

I couldn't even get to writing the print method. Wrote this recursive method above. Ran into an edge case with plains which was easy to fix, but while I was fixing it, the interviewer said time was up and left unhappily.

Seemed like the expectation was to write fully working code for printing the buildings with water and simulating the problem.

Do you folks any ideas on how I should have approached this, I was clearly not at the level they need.

Comments (5)