Difficulty: Easy, Asked-in: Amazon, Microsoft.
Key takeaway: An excellent problem to learn problem-solving by building partial solutions using a single loop.
Let’s understand the problem
Given an input array height[] representing the heights of buildings, write a program to count the number of buildings facing the sunset. It is assumed that the heights of all buildings are distinct.
Examples
Input: height[] = [7, 4, 8, 2, 9], Output: 3.
Explanation: As 7 is the first element, it can see the sunset. Similarly, 8 and 9 can see the sunset. 4 and 2 can't see the sunset because 7 and 8 are hiding it.
Input: height[] = [2, 3, 4, 5], Output: 4
Solution Idea using a single loop
For each building with height height[i], if the maximum height among the buildings from height[0] to height[i - 1] is less than height[i], then height[i] can see the sunset. Otherwise, a taller building in front of it will block its view.
The solution idea is to scan the height[] array from left to right while tracking two variables: the maximum height seen so far and the number of buildings facing the sun. If the current maximum height is less than height[i], update the maximum height to height[i] and increment the building count by 1.
Solution steps
- Before starting the loop, we initialise two variables: currMaxHeight to height[0] and buildingCount to 1.
- We run a loop from i = 1 to n − 1. At each iteration: If height[i] > currMaxHeight, we increment buildingCount by 1, update currMaxHeight to height[i], and move to the next iteration. Otherwise, the building with height height[i] is guaranteed to be hidden by the building with height currMaxHeight. It cannot see the sunset, so we ignore it.
- At the end of the loop, we return the value stored in buildingCount as the output.
Solution pseudocode
facingSunCount(height, n)
// The first building is visible from the sun
buildingCount = 1
currMaxHeight = height[0]
// Check each building from left to right
for i from 1 to n - 1
// A building is visible
// If it is taller than all previous buildings
if height[i] > currMaxHeight
buildingCount = buildingCount + 1
currMaxHeight = height[i]
return buildingCountTime and space complexity analysis
We are running loop n-1 times and doing O(1) operations at each iteration. So time complexity = O(n)* O(1) = O(n). We are using a constant number of variables, so space complexity = O(1).
Critical ideas to think!
- How can we modify the above code to also return the building that can see the sunset?
- How can we modify the above code when some buildings have the same height? Assume that a building of the same height will block the one after it.
- Is it possible to solve this problem using a stack?
Suggested coding questions to practice
- Valid mountain array
- The minimum and maximum value in an array
- Leaders in an array
- Roman to Integer
- Find equilibrium index of an array
Enjoy learning, Enjoy coding!
