Find minimum time to cross bridge with flashlight
NVIDIASoftware Engineer · Technical ScreenLast updated
This problem tests your ability to model a greedy strategy and handle state transitions under constraints to minimize the total time taken for a group to cross a bridge.
Problem Statement
There are n people standing on one side of a narrow bridge at night. They need to cross to the other side. The bridge can hold at most two people at a time, and they must carry a single flashlight to navigate safely. Since the bridge is dark, the flashlight must be passed back and forth between the people who have already crossed to those who have yet to cross.
Each person walks at a different speed. When two people cross together, they move at the speed of the slower person. Given an array speeds where speeds[i] is the time it takes for person i to cross the bridge, calculate the minimum total time required for everyone to reach the other side.
Function Signature
def min_bridge_time(speeds: List[int]) -> int:
Examples
Example 1:
Input: speeds = [1, 2, 5, 10]
Output: 17
Explanation:
- 1 and 2 cross (2 mins), 1 returns (1 min) [Total: 3]
- 5 and 10 cross (10 mins), 2 returns (2 mins) [Total: 15]
- 1 and 2 cross (2 mins) [Total: 17]
Example 2:
Input: speeds = [1, 3, 4]
Output: 8
Explanation: 1 and 3 cross (3 mins), 1 returns (1 min), 1 and 4 cross (4 mins). Total = 3 + 1 + 4 = 8.
Constraints
1 <= speeds.length <= 10001 <= speeds[i] <= 1000- The input array is not necessarily sorted.
Edge Cases
- One or two people: They simply cross together or individually.
- Large values in
speeds: Ensure integer overflow is not an issue (though not applicable here due to constraints).
Hints
Hint 1
Sort the speeds array first to easily identify the fastest and slowest individuals.
Hint 2
Consider the two optimal strategies to move the two slowest people across: either the fastest person shuttles everyone, or the two fastest people work together to move the two slowest.
Hint 3
For the two slowest people, compare the cost of (2 * fastest + slow1 + slow2) vs (fastest + 2 * second_fastest + slow1) to decide which shuttle pattern is more efficient.
Follow-up questions
- How would the solution change if the bridge had a maximum weight capacity, requiring you to group people differently?
- What if the flashlight had a battery life limit, and every trip consumed a specific amount of power?
- How would you modify your algorithm if there were two flashlights available, allowing two groups to potentially cross simultaneously?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.