Minimum Four-Walker Bridge Time
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Four hikers stand on the starting bank of an unlit canyon footbridge with a single lantern and want to bring everyone — along with the lantern — to the opposite bank in the shortest possible cumulative time.
def minimal_crossing_time(times: List[int]) -> int:
You are given times, a list of four positive integers where times[i] is the number of minutes hiker i needs to walk across the footbridge solo.
Movement Rules
- Occupancy limit: Never more than
2hikers may step onto the footbridge simultaneously. - Lantern requirement: Every crossing in either direction requires
1or2hikers physically carrying the lantern from one bank to the other (the lantern cannot be tossed across or moved without a walker). - Group pace: A solo trip takes that hiker's individual duration; a paired trip takes
max(time_a, time_b)because both walkers move together at the slower hiker's pace. - Input order:
timesis not guaranteed to be sorted, and multiple hikers may share the same duration.
Return the minimum total minutes needed for all four hikers and the lantern to finish on the destination bank.
Examples
Example 1
Input: times = [1, 2, 6, 9]
Output: 16
- Optimal 5-leg schedule:
(1, 2)cross forward (2min)1carries the lantern back (1min)(6, 9)cross forward together (9min — hiding6inside9's trip)2carries the lantern back (2min)(1, 2)cross forward (2min)
- Total time is
2 + 1 + 9 + 2 + 2 = 16minutes, beating the19minutes needed if hiker1escorted everyone individually (9 + 1 + 6 + 1 + 2).
Example 2
Input: times = [2, 6, 7, 11]
Output: 28
- Because the second-fastest hiker (
6) is nearly as slow as7, having hiker2escort each companion one by one is faster:(2, 11)forward (11),2back (2),(2, 7)forward (7),2back (2), and(2, 6)forward (6), totaling11 + 2 + 7 + 2 + 6 = 28minutes (compared to6 + 2 + 11 + 6 + 6 = 31if7and11paired up).
Example 3
Input: times = [14, 3, 1, 8]
Output: 24
- Sorting yields
[1, 3, 8, 14]. Pre-positioning3on the far bank so(8, 14)cross together costs3 + 1 + 14 + 3 + 3 = 24minutes, beating14 + 1 + 8 + 1 + 3 = 27.
Constraints
len(times) == 41 <= times[i] <= 10^9
Step-by-step walkthrough
Understand the rules and the bottleneck
Four people with individual walking times
t1 <= t2 <= t3 <= t4start on the near bank of a narrow bridge at night with a single flashlight (*):Near bank: [ t1, t2, t3, t4 ] * ====== bridge (max 2) ====== Far bank: [ ] Goal: [ ] ====== bridge (max 2) ====== Far bank: [ t1, t2, t3, t4 ] *Every move obeys three constraints: - Capacity: At most 2 people can walk on the bridge at once. - Flashlight: Every crossing (forward or backward) must carry the flashlight, so trips strictly alternate: forward, return, forward, return, ... - Pace: When two people cross together, they move at the pace of the slower person, costing
max(time_a, time_b).The automated judge calls
minimal_crossing_time(times)and checks the minimum total time, while an interviewer also expects you to explain which crossing sequence achieves it and why nothing can do better.Why any valid schedule needs at least five trips
Before guessing schedules, let's count how many bridge crossings are mathematically required.
Suppose a schedule makes
Fforward trips (near to far) andRreturn trips (far to near): - Because the flashlight starts on the near bank, alternates banks on every trip, and ends on the far bank, there is always one more forward trip than return trip:F = R + 1. - Each forward trip carries at most 2 people across (<= 2 * Fforward person-trips). - Each return trip carries at least 1 person back with the flashlight (>= 1 * Rbackward person-trips).Therefore, the net number of people moved to the far bank satisfies:
4 <= 2 * F - R = 2 * (R + 1) - R = R + 2Subtracting
2from both sides givesR >= 2return trips, and thereforeF = R + 1 >= 3forward trips — at least3 + 2 = 5trips in total. Moreover, to move all4people in exactly5trips (2 * 3 - 2 = 4), every forward trip must carry 2 people and every return trip must carry 1 person.Why the obvious first instinct can lose
Most people's first instinct is: "Have the fastest hiker
t1escort everyone across one by one, and lett1run the lantern back every time."Let's test that idea on Example 1 (
[1, 2, 6, 9]):Trip 1 (forward): (1, 9) cross -> costs 9 Trip 2 (return): 1 returns -> costs 1 Trip 3 (forward): (1, 6) cross -> costs 6 Trip 4 (return): 1 returns -> costs 1 Trip 5 (forward): (1, 2) cross -> costs 2 ------- Total: 19Can we beat
19? Look at Trips 1 and 3: we paid9for the slowest walker and another6for the second-slowest walker (9 + 6 = 15). If6and9crossed together on the same trip, their combined trip would costmax(6, 9) = 9—6would cross essentially for free inside9's slow walk!Build the two competing schedules (Plan A vs Plan B)
There is one catch if
(t3, t4)cross together: once they reach the far bank, who brings the flashlight back? Neithert3nort4should walk back, or we would payt3anyway! That means a fast helper (t2ort1) must already be waiting on the far bank before(t3, t4)start their crossing.Planting that fast helper on the far bank first gives Plan A, while using
t1as a solo escort gives Plan B:PLAN A: Pair the two slowest (t3, t4) PLAN B: Fastest (t1) escorts everyone ------------------------------------- ------------------------------------- Start: [t1, t2, t3, t4]* | [ ] Start: [t1, t2, t3, t4]* | [ ] 1. (t1, t2) -> cost t2 | [t1, t2]* 1. (t1, t4) -> cost t4 | [t1, t4]* 2. t1 <- cost t1 | [t2] 2. t1 <- cost t1 | [t4] 3. (t3, t4) -> cost t4 | [t2, t3, t4]* 3. (t1, t3) -> cost t3 | [t1, t3, t4]* 4. t2 <- cost t2 | [t3, t4] 4. t1 <- cost t1 | [t3, t4] 5. (t1, t2) -> cost t2 | [t1, t2, t3, t4]* 5. (t1, t2) -> cost t2 | [t1, t2, t3, t4]* Total A = t1 + 3*t2 + t4 Total B = 2*t1 + t2 + t3 + t4(In Plan A, swapping who returns first — sending
t2back on Step 2 andt1back on Step 4 — gives the exact same sumt1 + 3*t2 + t4.)Prove no third schedule can beat both plans
Why can no other sequence — even one with 7 or more trips — ever beat
min(Total A, Total B)? Split all possible valid schedules into two exhaustive cases based on howt3andt4get across:- Case 1:
t3andt4never cross forward together (or one of them walks back). Then one trip pays at leastt4, and a separate trip pays at leastt3. Because we need at least3forward trips and2returns:- if
t2crosses on a third trip separate fromt3andt4, that trip pays>= t2and the>= 2returns each pay>= t1, totaling at least2*t1 + t2 + t3 + t4(Total B); - if
t2rode witht3ort4, then eithert2walked back (>= t2) and crossed again (>= t2) — costing even more — ort1was already planted across via an extra round trip. Either way, you cannot pay less than Total B.
- if
- Case 2:
t3andt4cross forward together once (cost t4), and neither ever walks back. Notice that(t3, t4)cannot be the final trip: right before(t3, t4)leave the near bank, someone had to bring the flashlight to the near bank, so at least one of{t1, t2}is still on the near bank with them! And right after(t3, t4)arrive on the far bank, someone other thant3ort4must bring the flashlight back for that remaining person — so the other member of{t1, t2}must already be waiting on the far bank before(t3, t4)leave!- Getting one of
{t1, t2}onto the far bank with the flashlight back on the near bank costs at leastt2 + t1((t1, t2)over,t1back). - Crossing
(t3, t4)costst4. - Bringing the flashlight back with
t2and crossing(t1, t2)together costs at leastt2 + t2. - Summing those forced pieces gives
t2 + t1 + t4 + t2 + t2 = t1 + 3*t2 + t4(Total A).
- Getting one of
Subtracting the two totals isolates the exact trade-off:
Total A - Total B = (t1 + 3*t2 + t4) - (2*t1 + t2 + t3 + t4) = 2*t2 - (t1 + t3)Plan A saves
t1 + t3(no separatet3escort +t1return) at the price of2*t2(ferryingt2over and back). So Plan A wins when2*t2 < t1 + t3, Plan B wins when2*t2 > t1 + t3, and they tie when2*t2 == t1 + t3.- Case 1:
Trace all three examples
Let's check both formulas on our three example inputs:
Example 1: [1, 2, 6, 9] 2*t2 = 4 vs t1 + t3 = 7 -> Plan A wins! Plan A = 2 + 1 + 9 + 2 + 2 = 16 Plan B = 9 + 1 + 6 + 1 + 2 = 19 -> answer: 16 Example 2: [2, 6, 7, 11] 2*t2 = 12 vs t1 + t3 = 9 -> Plan B wins! (t2 = 6 is nearly as slow as t3 = 7) Plan A = 6 + 2 + 11 + 6 + 6 = 31 Plan B = 11 + 2 + 7 + 2 + 6 = 28 -> answer: 28 Example 3: [14, 3, 1, 8] (sorted -> [1, 3, 8, 14]) 2*t2 = 6 vs t1 + t3 = 9 -> Plan A wins! Plan A = 3 + 1 + 14 + 3 + 3 = 24 Plan B = 14 + 1 + 8 + 1 + 3 = 27 -> answer: 24Example 2 shows why neither plan alone passes all inputs: when the second-fastest walker
t2 = 6is sluggish compared tot1 = 2and close tot3 = 7, payingt2three times in Plan A costs more than lettingt1 = 2sprint back twice in Plan B!Implement the full solution
Sorting
timesfirst guaranteest1 <= t2 <= t3 <= t4even if a caller passes unsorted numbers, andmin(pair_slowest_cost, escort_each_cost)picks the winner in constant time:from typing import Any, Dict, List, Optional, Set, Tuple def minimal_crossing_time(times: List[int]) -> int: """Return the minimum total time for four people to cross a bridge with one flashlight.""" # Sort defensively so t1 <= t2 <= t3 <= t4 holds even if the input is unordered. t1, t2, t3, t4 = sorted(times) # Plan A (pair the two slowest so t3's walk is hidden inside t4's trip): # 1. (t1, t2) cross forward -> t2 (plants t2 on the far bank as a fast runner) # 2. t1 returns flashlight -> t1 # 3. (t3, t4) cross forward -> t4 (t3 rides alongside t4 at zero extra cost) # 4. t2 returns flashlight -> t2 (avoids sending t3 or t4 back!) # 5. (t1, t2) cross forward -> t2 pair_slowest_cost = t2 + t1 + t4 + t2 + t2 # Plan B (the single fastest runner t1 escorts everyone one by one): # 1. (t1, t4) cross forward -> t4 # 2. t1 returns flashlight -> t1 # 3. (t1, t3) cross forward -> t3 # 4. t1 returns flashlight -> t1 # 5. (t1, t2) cross forward -> t2 escort_each_cost = t4 + t1 + t3 + t1 + t2 # Plan A beats Plan B iff 2 * t2 < t1 + t3; taking min handles both cases and ties. return min(pair_slowest_cost, escort_each_cost)✅ Submit now — all tests should pass.
Intuition & how it works
Picture the shared lantern like a two-seat canoe that moves at the pace of the slower paddler, so someone on the destination bank always has to paddle it back until the final crossing. The slowest hiker (t4) must cross at least once, inevitably costing t4. Everything hinges on one strategic choice for the second-slowest hiker (t3): do we group t3 and t4 into the same crossing so t3's duration is completely absorbed inside t4's trip, or do we have the fastest sprinter (t1) escort each companion across individually?
Why does a naive greedy strategy (picking whichever single move looks cheapest right now, or always having t1 escort everyone) fall short? When t1 escorts t4 (cost t4), runs back (t1), escorts t3 (cost t3), runs back (t1), and escorts t2 (cost t2), we pay both t4 and t3 on separate trips! On Example 1 ([1, 2, 6, 9]), paying 9 and 6 separately wastes minutes when 2 is fast enough to ferry the lantern so 6 and 9 cross together for 9. Conversely, always grouping (t3, t4) loses when t2 is nearly as slow as t3 — as in Example 2 ([2, 6, 7, 11]) — because Plan A pays t2 three times!
Let's compare both schedules side by side on Example 1 ([1, 2, 6, 9]):
Plan A (pair 6 & 9, ferry with 1 & 2): Plan B (1 escorts everyone):
(1, 2) forward -> 2 (1, 9) forward -> 9
1 returns -> 1 1 returns -> 1
(6, 9) forward -> 9 (6 rides free!) (1, 6) forward -> 6
2 returns -> 2 1 returns -> 1
(1, 2) forward -> 2 (1, 2) forward -> 2
--------------------- --------------------
Total A = 16 (WINNER) Total B = 19
Evaluating Total A = t1 + 3*t2 + t4 alongside Total B = 2*t1 + t2 + t3 + t4 and returning min(Total A, Total B) yields the exact optimum for every four-walker input.
Complexity
- Time:
O(1). Sorting a fixed-length list of4integers performs at most5comparisons, and evaluating the two 5-term sums plusminexecutes a constant number of arithmetic operations. - Space:
O(1). Only the4unpacked integerst1, t2, t3, t4and two candidate totals are stored.
Edge cases
- Exact tie between both plans (
2 * t2 == t1 + t3): On[1, 3, 5, 9],2 * 3 == 1 + 5 == 6, so Plan A (3 + 1 + 9 + 3 + 3 = 19) and Plan B (9 + 1 + 5 + 1 + 3 = 19) tie at19; either schedule is optimal. - Tied durations (
t1 <= t2 <= t3 <= t4): Equal durations work identically. On[5, 5, 5, 5], all five crossings cost5for25; on[3, 3, 8, 9], two tied fastest runners yield3 + 3 + 9 + 3 + 3 = 21via Plan A. - Extreme outlier
t4(e.g.,[1, 2, 4, 100]): Both Plan A and Plan B payt4once, sot4cancels out when comparing the two plans (2 * 2 = 4 < 1 + 4 = 5selects Plan A =107over Plan B =108). - Unsorted input list: Calling
sorted(times)up front handles arbitrary orderings such as Example 3 ([14, 3, 1, 8]->24). - Large integer values: Python integers have unlimited precision; in C++ or Java,
5 * t4overflows signed 32-bitintoncet4 > 4.29 * 10^8, requiring a 64-bit integer (long long/long).
Common mistakes
- Committing to only Plan B ("fastest escorts everyone"): Fails Examples 1 and 3 (
19instead of16on[1, 2, 6, 9];27instead of24on[14, 3, 1, 8]). - Committing to only Plan A ("always pair the two slowest"): Fails Example 2 (
31instead of28on[2, 6, 7, 11], where2 * 6 > 2 + 7). - Sending
(t3, t4)across on the very first trip: With nobody waiting on the far bank, eithert3ort4must walk the lantern back, wasting at leastt3. - Adding a pair's durations instead of taking
max: Two walkers share the bridge concurrently, so(t3, t4)costsmax(t3, t4) = t4, nevert3 + t4. - Omitting return trips: Every forward crossing before the last one requires someone on the far bank to carry the lantern back.
Alternative approaches
- Shortest-path search on the state-space graph: Represent each puzzle configuration as
(near_mask, lantern_side), wherenear_maskis a 4-bit bitmask (an integer whosei-th binary bit is1when hikeristands on the starting bank and0when on the destination bank), forming2^4 * 2 = 32nodes in a state-space graph (a graph whose vertices are configurations and whose weighted edges are valid crossings). Running Dijkstra's algorithm (a priority-queue search that always expands the lowest-elapsed-time reachable state next) finds the optimal total automatically and serves as a randomized test oracle, though itsO(n^2 * 2^n)runtime grows exponentially with party sizen.
Follow-up questions
- How does this optimal strategy generalize when N walkers with arbitrary positive crossing times need to cross? Sort the durations
t_1 <= t_2 <= ... <= t_Nand repeatedly deliver the two slowest remaining hikers (t_(n-1)andt_n) in a 4-trip cycle that returnst_1,t_2, and the lantern to the starting bank: either ferry them together via Plan A's 4-trip prefix (t_2 + t_1 + t_n + t_2 = t_1 + 2*t_2 + t_n) or havet_1escort each separately via Plan B's 4-trip prefix (t_n + t_1 + t_(n-1) + t_1 = 2*t_1 + t_(n-1) + t_n), addingmin(...)and shrinkingnby2per round. Oncen <= 3, finish the base case (t_1 + t_2 + t_3forn = 3,t_2forn = 2,t_1forn = 1), solving theN-walker problem inO(N log N)time andO(1)extra space. - How would you modify the function to return the step-by-step schedule of crossings alongside the minimum total time? Model each leg as
(direction, walkers, leg_cost)— such as("forward", (t1, t2), t2)and("back", (t1,), t1)— build the 5-tuple schedule for Plan A and the 5-tuple schedule for Plan B, and return whichever schedule has the smaller totalleg_cost(along with that total). In a state-space Dijkstra solver, storeparent[next_state] = (curr_state, move)whenever a shorter path is discovered and backtrack from(0, 1)to((1 << n) - 1, 0), reversing the recorded legs. - What changes if the bridge can accommodate up to K walkers simultaneously for K >= 3? Batching slow hikers becomes even more effective because one
t_Ncrossing can absorb up toK - 1slower companions (t_(N-K+2) ... t_(N-1)) at once, provided enough fast runners have already been stationed on the far bank to bring the lantern back after slow batches cross. SmallNcan be solved directly via Dijkstra over2^N * 2states (enumerating subsets of size1..K), while largerNcan be solved with dynamic programming over the sorted prefix using only the fastestK - 1hikers as return couriers.
Follow-up questions
- How does this optimal strategy generalize when N walkers with arbitrary positive crossing times need to cross?
- How would you modify the function to return the step-by-step schedule of crossings alongside the minimum total time?
- What changes if the bridge can accommodate up to K walkers simultaneously for K >= 3?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array