Thursday, January 28, 2016

Coding Challenge: water collected between towers, part 2

This is continuation of part 1.

In this post, we will solve this challenge using dynamic programming techniques and property observers.

Dynamic programming approach with property observers

This approach solves the challenge by dividing the problem into small chunks.  For each tower, the height of tallest tower to the right is determined by comparing the tower's own height and reported height of tallest tower of the right neighbor, i.e. 

tallest2right = max(self.height, rightTower. tallest2right)

And the height of tallest tower to the left is determined in a similar fashion.  Each tower does not scan the entire array to determine tallest tower heights to either direction--it simply uses the reported value from neighbor towers to evaluate their own answers.  The neighboring towers may use pre-calculated value or perform calculation on as-needed basis.  In this implementation, the values are calculated and stored for each topography change (i.e. modifications to leftTower or rightTower), and the change is propagated by notifying neighbor towers.

The initial value of tallest tower to either direction is set to own height.  As each tower connects to its neighbors, messages are sent to appropriate towers to update their value of tallest towers in both direction via property observer didSet().  Here's definition for Tower class.

Coding Challenge: water collected between towers, part 1

I came across a post on StackOverflow on an interview question asked by Amazon, and wanted to share my solution.  The question goes like this:

You are given an array representing heights of towers.  It starts raining.  Determine how much water is collected between the towers, assuming each tower has width of 1.

Example:
Input: [3, 4, 2, 7, 4, 3, 8, 2, 4]
Expected Output: 11 units of water

            *     
      * W W *     
      * W W *     
      * W W *     
  * W * * W * W * 
* * W * * * * W * 
* * * * * * * * * 
* * * * * * * * * 


The problem can be solved in two ways, either iteratively or recursively with dynamic programming. Both rely on the observation that the amount of water collected atop any tower is determined by the shortest of the tallest tower to the left and right of itself.  The iterative solution is presented.