Largest Valid Carpool Group Under Co-Rider Bounds

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

You are coordinating a shared shuttle pool with N prospective passengers indexed 0 through N - 1. Each person i specifies a personal comfort range [low[i], high[i]] for how many co-riders (other passengers in the vehicle, excluding person i) they will tolerate on the ride.

Whenever you form a group of k passengers (1 <= k <= N), every member of that group rides alongside k - 1 co-riders. A group of size k is valid only if low[i] <= k - 1 <= high[i] holds for every selected member i. People left out of the shuttle do not affect validity, and the shuttle itself can hold up to all N people.

Implement

def max_group_size(low: list[int], high: list[int]) -> int:

to compute the maximum valid group size k, or 0 when not even a single-passenger or multi-passenger group can satisfy all of its members. Your algorithm must run in O(N) time.

Examples

Example 1

Input: low = [1, 0, 2, 2, 3, 1], high = [3, 2, 4, 3, 5, 3]
Output: 4

Walk-through: Passengers 0, 2, 3, 4, 5 all include 3 inside their [low[i], high[i]] interval, so picking any 4 of those five people gives each chosen passenger 4 - 1 = 3 co-riders and satisfies everyone aboard. Size 5 (4 co-riders) only works for passengers 2 and 4, and size 6 (5 co-riders) only works for passenger 4, so neither larger size has enough eligible people.

Example 2

Input: low = [3, 0, 3, 3, 3], high = [4, 0, 3, 5, 3]
Output: 4

Walk-through: Passenger 1 only rides solo (0 co-riders), making k = 1 valid while k = 2 and k = 3 are both impossible. However, passengers 0, 2, 3, 4 all accept 3 co-riders, so those four can travel together for k = 4. Size 5 fails because only passengers 0 and 3 accept 4 co-riders.

Example 3

Input: low = [1, 3, 2], high = [1, 6, 4]
Output: 0

Walk-through: Nobody accepts 0 co-riders (k = 1 fails), only passenger 0 accepts 1 co-rider (k = 2 fails), and only passenger 2 accepts 2 co-riders (k = 3 fails, since passenger 1 demands at least 3 co-riders). Because every non-empty size fails, the answer is 0.

Constraints

  • 1 <= N <= 10^5, where N = len(low) == len(high)
  • 0 <= low[i] <= high[i] <= 10^9 for every 0 <= i < N
  • Target time complexity: O(N)

Step-by-step walkthrough

  1. Separate group size k from co-rider count k - 1

    Passenger i tolerates between low[i] and high[i] co-riders (other passengers in the shuttle), inclusive. Whenever k people board the shuttle together, each person inside rides alongside k - 1 co-riders:

    group size      = k        (1 .. N passengers aboard)
    co-rider count  = k - 1    (0 .. N - 1 other passengers aboard)
    member rule     : low[i] <= k - 1 <= high[i]  for every selected passenger i
    

    People who stay behind place zero restrictions on the trip. With 1 <= N <= 10^5 and bounds up to 10^9, we want the largest valid k (or 0 when even k = 1 fails) in O(N) time.

  2. Reduce subset selection to counting willing people

    Choosing among 2^N subsets looks intimidating until we fix a candidate group size k and ask: which people could legally sit inside a shuttle of size k?

    Only people whose interval [low[i], high[i]] covers m = k - 1. Let willing[m] be how many people have low[i] <= m <= high[i]:

    • If willing[k - 1] < k: Even taking every person who tolerates k - 1 co-riders leaves fewer than k passengers, so size k is impossible.
    • If willing[k - 1] >= k: Select any k of those willing people and leave the remaining willing[k - 1] - k behind. Every selected person sees k - 1 co-riders and accepts k - 1, so size k is always valid!

    Subset search vanishes completely: a valid group of size k exists if and only if willing[k - 1] >= k.

  3. Why nested loops are O(N^2) and binary search fails

    Two common shortcuts go wrong here:

    1. Nested loop (O(N^2)): Scanning all N people for each candidate k from N down to 1 performs N^2 = 10^10 checks at N = 10^5, exceeding time limits.
    2. Binary searching on k (incorrect): Binary search needs a monotonic YES, ..., YES, NO, ..., NO boundary, whereas group-size validity can contain gaps:
    low = [3, 0, 3, 3, 3], high = [4, 0, 3, 5, 3]   (Example 2, N = 5)
    
    group size k   :   1     2     3     4     5
    co-riders k - 1:   0     1     2     3     4
    willing[k - 1] :   1     0     0     4     2
    valid (>= k)?  :  YES   NO    NO    YES   NO
    

    Here k = 4 succeeds even though k = 2 and k = 3 both fail! Probing mid = 3, seeing NO, and discarding sizes >= 3 would wrongly return 1 instead of 4. We must inspect willing[m] across all m in 0..N-1.

  4. Clamp co-rider counts to 0..N-1 and use a difference array

    How can we build willing[0..N-1] in O(N) time when high[i] reaches 10^9?

    Observe that among N total people, nobody can ever ride with more than N - 1 co-riders: - If low[i] > N - 1, person i requires more co-riders than exist in the entire pool — skip person i. - If high[i] > N - 1, cap the upper endpoint at end = min(high[i], N - 1).

    Now each remaining person adds +1 to every integer m in [start, end] within 0..N-1. Rather than looping across [start, end], use a difference array diff of length N + 1: add +1 at start (where the interval begins) and -1 at end + 1 (one slot past where it ends). A single left-to-right running sum converts those two endpoint markers into +1 across the whole range:

    Add +1 to [1, 3] on indices 0..4 (diff has length 6):
      index m   :   0    1    2    3    4   (5)
      diff      : [ 0,  +1,   0,   0,  -1,   0 ]
      prefix sum: [ 0,   1,   1,   1,   0 ]      <- +1 on 1..3 in two O(1) writes!
    
  5. Code the linear-time solution

    Combining the three linear passes — mark intervals in diff, accumulate prefix sums into willing, and scan k from n down to 1 — runs in O(N) time and O(N) space:

    def max_group_size(low: list[int], high: list[int]) -> int:
        n = len(low)
        if n == 0:
            return 0
    
        # Phase 1: record each passenger's tolerated co-rider interval [start, end].
        # Even when all n people board together, each person sees at most n - 1 co-riders,
        # so only co-rider counts m in 0..n-1 can ever produce a valid group.
        # diff: difference array of length n + 1 where +1 opens a range at `start`
        # and -1 closes it at `end + 1` (index n serves as a sentinel slot).
        diff = [0] * (n + 1)
        for i in range(n):
            if low[i] > n - 1:
                # Demands more co-riders than exist among the remaining n - 1 people.
                continue
            start = low[i]
            end = min(high[i], n - 1)  # clamp large high[i] (up to 10^9) down to n - 1
            diff[start] += 1
            diff[end + 1] -= 1
    
        # Phase 2: accumulate a left-to-right prefix sum over `diff`.
        # willing[m] = number of people whose [low[i], high[i]] covers m co-riders.
        willing = [0] * n
        running_riders = 0
        for m in range(n):
            running_riders += diff[m]
            willing[m] = running_riders
    
        # Phase 3: check candidate group sizes k from largest (n) down to smallest (1).
        # A group of k people gives each member k - 1 co-riders, and works iff at least k
        # people tolerate k - 1 co-riders. Feasibility is non-monotonic, so test every k.
        for k in range(n, 0, -1):
            companions = k - 1
            if willing[companions] >= k:
                return k
    
        return 0
    
  6. Walk through Example 2 step by step

    Trace low = [3, 0, 3, 3, 3], high = [4, 0, 3, 5, 3] (n = 5, valid co-rider counts 0..4):

    Phase 1 (interval markers on diff[0..5]):
      person 0: [3, 4]             -> diff[3] += 1, diff[5] -= 1
      person 1: [0, 0]             -> diff[0] += 1, diff[1] -= 1
      person 2: [3, 3]             -> diff[3] += 1, diff[4] -= 1
      person 3: [3, min(5, 4) = 4] -> diff[3] += 1, diff[5] -= 1
      person 4: [3, 3]             -> diff[3] += 1, diff[4] -= 1
      => diff = [1, -1, 0, 4, -2, -2]
    
    Phase 2 (prefix sums -> willing[0..4]):
      m = 0: running = 0 + 1 = 1
      m = 1: running = 1 - 1 = 0
      m = 2: running = 0 + 0 = 0
      m = 3: running = 0 + 4 = 4
      m = 4: running = 4 - 2 = 2
      => willing = [1, 0, 0, 4, 2]
    
    Phase 3 (scan k from 5 down to 1):
      k = 5 (companions = 4): willing[4] = 2 < 5  -> no
      k = 4 (companions = 3): willing[3] = 4 >= 4 -> YES! Return 4.
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def max_group_size(low: list[int], high: list[int]) -> int:
        n = len(low)
        if n == 0:
            return 0
    
        # Phase 1: record each passenger's tolerated co-rider interval [start, end].
        # Even when all n people board together, each person sees at most n - 1 co-riders,
        # so only co-rider counts m in 0..n-1 can ever produce a valid group.
        # diff: difference array of length n + 1 where +1 opens a range at `start`
        # and -1 closes it at `end + 1` (index n serves as a sentinel slot).
        diff = [0] * (n + 1)
        for i in range(n):
            if low[i] > n - 1:
                # Demands more co-riders than exist among the remaining n - 1 people.
                continue
            start = low[i]
            end = min(high[i], n - 1)  # clamp large high[i] (up to 10^9) down to n - 1
            diff[start] += 1
            diff[end + 1] -= 1
    
        # Phase 2: accumulate a left-to-right prefix sum over `diff`.
        # willing[m] = number of people whose [low[i], high[i]] covers m co-riders.
        willing = [0] * n
        running_riders = 0
        for m in range(n):
            running_riders += diff[m]
            willing[m] = running_riders
    
        # Phase 3: check candidate group sizes k from largest (n) down to smallest (1).
        # A group of k people gives each member k - 1 co-riders, and works iff at least k
        # people tolerate k - 1 co-riders. Feasibility is non-monotonic, so test every k.
        for k in range(n, 0, -1):
            companions = k - 1
            if willing[companions] >= k:
                return k
    
        return 0
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine posting a separate signup sheet for every possible shuttle headcount k from 1 to N. Inside a shuttle holding k passengers, every person aboard rides alongside m = k - 1 co-riders, so person i signs sheet k whenever low[i] <= k - 1 <= high[i]. If at least k people sign sheet k, we can board any k of those volunteers (leaving extra signers behind, since unchosen people impose no rules); if fewer than k people sign, no subset of size k can possibly work.

To count all N signup totals in linear time, observe that N people can never produce more than N - 1 co-riders, so we clamp high[i] down to N - 1 and mark each person's [start, end] range in a difference array (an array where adding +1 at start and -1 at end + 1 encodes an entire range increment in two O(1) writes). One prefix sum pass (a left-to-right running total) turns diff into willing[m] for every m in 0..N-1, and scanning k from N down to 1 returns the first k with willing[k - 1] >= k.

A brute-force check that scans all N people for each candidate size k takes O(N^2) time (10^10 steps at N = 10^5), sorting interval endpoints takes O(N log N) time (missing the O(N) target), and binary searching on k fails outright because valid group sizes are not monotonic — a group of 4 can succeed even when sizes 2 and 3 are both impossible!

Mini walkthrough: Take Example 2 with low = [3, 0, 3, 3, 3] and high = [4, 0, 3, 5, 3] (N = 5). Clamping high[3] = 5 to 4 and marking [3, 4] twice, [3, 3] twice, and [0, 0] once in diff[0..5] yields diff = [1, -1, 0, 4, -2, -2]. Accumulating prefix sums gives willing = [1, 0, 0, 4, 2] for m = 0..4 co-riders. Testing downward: k = 5 needs willing[4] >= 5 (2 < 5, fails), and k = 4 needs willing[3] >= 4 (4 >= 4, succeeds!), returning 4.

Complexity

  • Time O(N): Phase 1 inspects each of the N passengers once and performs two O(1) array writes; Phase 2 walks N co-rider counts once to accumulate running totals; Phase 3 tests at most N group sizes in O(1) time each, with zero sorting.
  • Space O(N): diff stores N + 1 integers and willing stores N integers, because capping high[i] at N - 1 bounds memory by N (<= 10^5) instead of max(high) (<= 10^9).

Edge cases

  • Single passenger (N = 1): Only k = 1 (0 co-riders) exists; returns 1 when low[0] == 0 and 0 otherwise.
  • No valid group (0 returned): In low = [1, 3, 2], high = [1, 6, 4] (Example 3), nobody rides solo, only one person accepts 1 co-rider, and only one accepts 2 co-riders, so the downward scan finishes and returns 0.
  • low[i] > N - 1 or high[i] == 10^9: People with low[i] > N - 1 are skipped before indexing diff, and high[i] is clamped to N - 1 so end + 1 <= N stays in bounds.
  • Surplus volunteers (willing[k - 1] > k): Five people with low = high = [1, 1, 1, 1, 1] produce willing[1] = 5 >= 2, returning k = 2 (boarding all 5 would give each person 4 co-riders, violating high[i] = 1).
  • Non-monotonic gaps: Inputs like Example 2 succeed at k = 1 and k = 4 while failing at k = 2, 3, 5; checking every k from N down to 1 never misses 4.

Common mistakes

  • Binary searching on group size k: Because validity has holes, a failed midpoint mid says nothing about whether larger group sizes above mid are feasible.
  • Mixing up k (group size) and k - 1 (co-riders): Checking willing[k] >= k instead of willing[k - 1] >= k shifts every lookup by 1 and goes out of range at k = N.
  • Sizing diff to max(high) + 2: When high[i] = 10^9, allocating a billion slots exhausts time and memory; clamping end = min(high[i], n - 1) is mandatory.
  • Omitting if low[i] > n - 1: continue: Without this guard, start = low[i] can exceed n and raise IndexError on diff[start], or invert [start, end].
  • Ignoring low[i] and only testing high[i] >= k - 1: Someone with low[i] = 3 refuses smaller groups of 1, 2, or 3 passengers.

Alternative approaches

  • Endpoint sorting + sweep line (O(N log N)): Emit (start, +1) and (end + 1, -1) events, sort them, and sweep across m. Although correct, sorting costs O(N log N) and misses the strict O(N) requirement; clamping endpoints to 0..N lets diff bucket events directly in O(N).
  • In-place prefix sum (O(N) with a single array): Accumulate diff[m] += diff[m - 1] directly inside diff instead of creating willing. Keeping willing separate in solution.py makes interval markers vs. passenger counts clearer on a first read.

Follow-up questions

  • How does the algorithm change if the van itself holds at most C passengers? Every passenger's rule for a group of size k stays identical; we simply cannot exceed C seats. Leave Phases 1 and 2 untouched and start Phase 3 at for k in range(min(n, C), 0, -1):, preserving O(N) time and O(N) space.
  • How would you return the indices of the people selected for an optimal group? Once Phase 3 finds the maximum valid k (returning [] if k == 0), make one additional O(N) pass over i = 0..n-1, appending each index i that satisfies low[i] <= k - 1 <= high[i] and stopping as soon as k indices have been collected.
  • How would you maintain the maximum valid group size dynamically as people join or leave the pool? Fix an upper bound M on pool size and maintain surplus[m] = willing[m] - (m + 1) for m in 0..M-1; size k = m + 1 is valid iff surplus[m] >= 0 (for m + 1 above the current active pool size, willing[m] < m + 1 holds automatically). Store surplus[0..M-1] in a segment tree (a binary tree over an array supporting O(log M) range additions and rightmost-index queries where the subtree maximum is >= 0), handling each join, leave, and max-group query in O(log M) time.

Follow-up questions

Similar questions

More Uber Freight interview questions

All 4 Uber Freight questions →