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 2 hikers may step onto the footbridge simultaneously.
  • Lantern requirement: Every crossing in either direction requires 1 or 2 hikers 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: times is 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. (1, 2) cross forward (2 min)
    2. 1 carries the lantern back (1 min)
    3. (6, 9) cross forward together (9 min — hiding 6 inside 9's trip)
    4. 2 carries the lantern back (2 min)
    5. (1, 2) cross forward (2 min)
  • Total time is 2 + 1 + 9 + 2 + 2 = 16 minutes, beating the 19 minutes needed if hiker 1 escorted 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 as 7, having hiker 2 escort each companion one by one is faster: (2, 11) forward (11), 2 back (2), (2, 7) forward (7), 2 back (2), and (2, 6) forward (6), totaling 11 + 2 + 7 + 2 + 6 = 28 minutes (compared to 6 + 2 + 11 + 6 + 6 = 31 if 7 and 11 paired up).

Example 3

Input: times = [14, 3, 1, 8]
Output: 24
  • Sorting yields [1, 3, 8, 14]. Pre-positioning 3 on the far bank so (8, 14) cross together costs 3 + 1 + 14 + 3 + 3 = 24 minutes, beating 14 + 1 + 8 + 1 + 3 = 27.

Constraints

  • len(times) == 4
  • 1 <= times[i] <= 10^9

Step-by-step walkthrough

  1. Understand the rules and the bottleneck

    Four people with individual walking times t1 <= t2 <= t3 <= t4 start 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.

  2. 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 F forward trips (near to far) and R return 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 * F forward person-trips). - Each return trip carries at least 1 person back with the flashlight (>= 1 * R backward person-trips).

    Therefore, the net number of people moved to the far bank satisfies:

    4  <=  2 * F - R  =  2 * (R + 1) - R  =  R + 2
    

    Subtracting 2 from both sides gives R >= 2 return trips, and therefore F = R + 1 >= 3 forward trips — at least 3 + 2 = 5 trips in total. Moreover, to move all 4 people in exactly 5 trips (2 * 3 - 2 = 4), every forward trip must carry 2 people and every return trip must carry 1 person.

  3. Why the obvious first instinct can lose

    Most people's first instinct is: "Have the fastest hiker t1 escort everyone across one by one, and let t1 run 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:      19
    

    Can we beat 19? Look at Trips 1 and 3: we paid 9 for the slowest walker and another 6 for the second-slowest walker (9 + 6 = 15). If 6 and 9 crossed together on the same trip, their combined trip would cost max(6, 9) = 9 — 6 would cross essentially for free inside 9's slow walk!

  4. 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? Neither t3 nor t4 should walk back, or we would pay t3 anyway! That means a fast helper (t2 or t1) 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 t1 as 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 t2 back on Step 2 and t1 back on Step 4 — gives the exact same sum t1 + 3*t2 + t4.)

  5. 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 how t3 and t4 get across:

    • Case 1: t3 and t4 never cross forward together (or one of them walks back). Then one trip pays at least t4, and a separate trip pays at least t3. Because we need at least 3 forward trips and 2 returns:
      • if t2 crosses on a third trip separate from t3 and t4, that trip pays >= t2 and the >= 2 returns each pay >= t1, totaling at least 2*t1 + t2 + t3 + t4 (Total B);
      • if t2 rode with t3 or t4, then either t2 walked back (>= t2) and crossed again (>= t2) — costing even more — or t1 was already planted across via an extra round trip. Either way, you cannot pay less than Total B.
    • Case 2: t3 and t4 cross 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 than t3 or t4 must 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 least t2 + t1 ((t1, t2) over, t1 back).
      • Crossing (t3, t4) costs t4.
      • Bringing the flashlight back with t2 and crossing (t1, t2) together costs at least t2 + t2.
      • Summing those forced pieces gives t2 + t1 + t4 + t2 + t2 = t1 + 3*t2 + t4 (Total A).

    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 separate t3 escort + t1 return) at the price of 2*t2 (ferrying t2 over and back). So Plan A wins when 2*t2 < t1 + t3, Plan B wins when 2*t2 > t1 + t3, and they tie when 2*t2 == t1 + t3.

  6. 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: 24
    

    Example 2 shows why neither plan alone passes all inputs: when the second-fastest walker t2 = 6 is sluggish compared to t1 = 2 and close to t3 = 7, paying t2 three times in Plan A costs more than letting t1 = 2 sprint back twice in Plan B!

  7. Implement the full solution

    Sorting times first guarantees t1 <= t2 <= t3 <= t4 even if a caller passes unsorted numbers, and min(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 of 4 integers performs at most 5 comparisons, and evaluating the two 5-term sums plus min executes a constant number of arithmetic operations.
  • Space: O(1). Only the 4 unpacked integers t1, t2, t3, t4 and 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 at 19; either schedule is optimal.
  • Tied durations (t1 <= t2 <= t3 <= t4): Equal durations work identically. On [5, 5, 5, 5], all five crossings cost 5 for 25; on [3, 3, 8, 9], two tied fastest runners yield 3 + 3 + 9 + 3 + 3 = 21 via Plan A.
  • Extreme outlier t4 (e.g., [1, 2, 4, 100]): Both Plan A and Plan B pay t4 once, so t4 cancels out when comparing the two plans (2 * 2 = 4 < 1 + 4 = 5 selects Plan A = 107 over 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 * t4 overflows signed 32-bit int once t4 > 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 (19 instead of 16 on [1, 2, 6, 9]; 27 instead of 24 on [14, 3, 1, 8]).
  • Committing to only Plan A ("always pair the two slowest"): Fails Example 2 (31 instead of 28 on [2, 6, 7, 11], where 2 * 6 > 2 + 7).
  • Sending (t3, t4) across on the very first trip: With nobody waiting on the far bank, either t3 or t4 must walk the lantern back, wasting at least t3.
  • Adding a pair's durations instead of taking max: Two walkers share the bridge concurrently, so (t3, t4) costs max(t3, t4) = t4, never t3 + 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), where near_mask is a 4-bit bitmask (an integer whose i-th binary bit is 1 when hiker i stands on the starting bank and 0 when on the destination bank), forming 2^4 * 2 = 32 nodes 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 its O(n^2 * 2^n) runtime grows exponentially with party size n.

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_N and repeatedly deliver the two slowest remaining hikers (t_(n-1) and t_n) in a 4-trip cycle that returns t_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 have t_1 escort 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), adding min(...) and shrinking n by 2 per round. Once n <= 3, finish the base case (t_1 + t_2 + t_3 for n = 3, t_2 for n = 2, t_1 for n = 1), solving the N-walker problem in O(N log N) time and O(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 total leg_cost (along with that total). In a state-space Dijkstra solver, store parent[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_N crossing can absorb up to K - 1 slower 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. Small N can be solved directly via Dijkstra over 2^N * 2 states (enumerating subsets of size 1..K), while larger N can be solved with dynamic programming over the sorted prefix using only the fastest K - 1 hikers as return couriers.

Follow-up questions

Similar questions

More Exoduspoint interview questions

All 1 Exoduspoint questions →