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, whereN = len(low) == len(high)0 <= low[i] <= high[i] <= 10^9for every0 <= i < N- Target time complexity:
O(N)
Step-by-step walkthrough
Separate group size k from co-rider count k - 1
Passenger
itolerates betweenlow[i]andhigh[i]co-riders (other passengers in the shuttle), inclusive. Wheneverkpeople board the shuttle together, each person inside rides alongsidek - 1co-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 iPeople who stay behind place zero restrictions on the trip. With
1 <= N <= 10^5and bounds up to10^9, we want the largest validk(or0when evenk = 1fails) inO(N)time.Reduce subset selection to counting willing people
Choosing among
2^Nsubsets looks intimidating until we fix a candidate group sizekand ask: which people could legally sit inside a shuttle of sizek?Only people whose interval
[low[i], high[i]]coversm = k - 1. Letwilling[m]be how many people havelow[i] <= m <= high[i]:- If
willing[k - 1] < k: Even taking every person who toleratesk - 1co-riders leaves fewer thankpassengers, so sizekis impossible. - If
willing[k - 1] >= k: Select anykof those willing people and leave the remainingwilling[k - 1] - kbehind. Every selected person seesk - 1co-riders and acceptsk - 1, so sizekis always valid!
Subset search vanishes completely: a valid group of size
kexists if and only ifwilling[k - 1] >= k.- If
Why nested loops are O(N^2) and binary search fails
Two common shortcuts go wrong here:
- Nested loop (
O(N^2)): Scanning allNpeople for each candidatekfromNdown to1performsN^2 = 10^10checks atN = 10^5, exceeding time limits. - Binary searching on
k(incorrect): Binary search needs a monotonicYES, ..., YES, NO, ..., NOboundary, 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 NOHere
k = 4succeeds even thoughk = 2andk = 3both fail! Probingmid = 3, seeingNO, and discarding sizes>= 3would wrongly return1instead of4. We must inspectwilling[m]across allmin0..N-1.- Nested loop (
Clamp co-rider counts to 0..N-1 and use a difference array
How can we build
willing[0..N-1]inO(N)time whenhigh[i]reaches10^9?Observe that among
Ntotal people, nobody can ever ride with more thanN - 1co-riders: - Iflow[i] > N - 1, personirequires more co-riders than exist in the entire pool — skip personi. - Ifhigh[i] > N - 1, cap the upper endpoint atend = min(high[i], N - 1).Now each remaining person adds
+1to every integermin[start, end]within0..N-1. Rather than looping across[start, end], use a difference arraydiffof lengthN + 1: add+1atstart(where the interval begins) and-1atend + 1(one slot past where it ends). A single left-to-right running sum converts those two endpoint markers into+1across 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!Code the linear-time solution
Combining the three linear passes — mark intervals in
diff, accumulate prefix sums intowilling, and scankfromndown to1— runs inO(N)time andO(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 0Walk through Example 2 step by step
Trace
low = [3, 0, 3, 3, 3],high = [4, 0, 3, 5, 3](n = 5, valid co-rider counts0..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.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 theNpassengers once and performs twoO(1)array writes; Phase 2 walksNco-rider counts once to accumulate running totals; Phase 3 tests at mostNgroup sizes inO(1)time each, with zero sorting. - Space
O(N):diffstoresN + 1integers andwillingstoresNintegers, because cappinghigh[i]atN - 1bounds memory byN(<= 10^5) instead ofmax(high)(<= 10^9).
Edge cases
- Single passenger (
N = 1): Onlyk = 1(0co-riders) exists; returns1whenlow[0] == 0and0otherwise. - No valid group (
0returned): Inlow = [1, 3, 2], high = [1, 6, 4](Example 3), nobody rides solo, only one person accepts1co-rider, and only one accepts2co-riders, so the downward scan finishes and returns0. low[i] > N - 1orhigh[i] == 10^9: People withlow[i] > N - 1are skipped before indexingdiff, andhigh[i]is clamped toN - 1soend + 1 <= Nstays in bounds.- Surplus volunteers (
willing[k - 1] > k): Five people withlow = high = [1, 1, 1, 1, 1]producewilling[1] = 5 >= 2, returningk = 2(boarding all5would give each person4co-riders, violatinghigh[i] = 1). - Non-monotonic gaps: Inputs like Example 2 succeed at
k = 1andk = 4while failing atk = 2, 3, 5; checking everykfromNdown to1never misses4.
Common mistakes
- Binary searching on group size
k: Because validity has holes, a failed midpointmidsays nothing about whether larger group sizes abovemidare feasible. - Mixing up
k(group size) andk - 1(co-riders): Checkingwilling[k] >= kinstead ofwilling[k - 1] >= kshifts every lookup by1and goes out of range atk = N. - Sizing
difftomax(high) + 2: Whenhigh[i] = 10^9, allocating a billion slots exhausts time and memory; clampingend = min(high[i], n - 1)is mandatory. - Omitting
if low[i] > n - 1: continue: Without this guard,start = low[i]can exceednand raiseIndexErrorondiff[start], or invert[start, end]. - Ignoring
low[i]and only testinghigh[i] >= k - 1: Someone withlow[i] = 3refuses smaller groups of1,2, or3passengers.
Alternative approaches
- Endpoint sorting + sweep line (
O(N log N)): Emit(start, +1)and(end + 1, -1)events, sort them, and sweep acrossm. Although correct, sorting costsO(N log N)and misses the strictO(N)requirement; clamping endpoints to0..Nletsdiffbucket events directly inO(N). - In-place prefix sum (
O(N)with a single array): Accumulatediff[m] += diff[m - 1]directly insidediffinstead of creatingwilling. Keepingwillingseparate insolution.pymakes 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
kstays identical; we simply cannot exceedCseats. Leave Phases 1 and 2 untouched and start Phase 3 atfor k in range(min(n, C), 0, -1):, preservingO(N)time andO(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[]ifk == 0), make one additionalO(N)pass overi = 0..n-1, appending each indexithat satisfieslow[i] <= k - 1 <= high[i]and stopping as soon askindices have been collected. - How would you maintain the maximum valid group size dynamically as people join or leave the pool? Fix an upper bound
Mon pool size and maintainsurplus[m] = willing[m] - (m + 1)form in 0..M-1; sizek = m + 1is valid iffsurplus[m] >= 0(form + 1above the current active pool size,willing[m] < m + 1holds automatically). Storesurplus[0..M-1]in a segment tree (a binary tree over an array supportingO(log M)range additions and rightmost-index queries where the subtree maximum is>= 0), handling each join, leave, and max-group query inO(log M)time.
Follow-up questions
- How does the algorithm change if the van itself holds at most C passengers?
- How would you return the indices of the people selected for an optimal group?
- How would you maintain the maximum valid group size dynamically as people join or leave the pool?
Similar questions
- Distributed Link Shortener for Extreme Redirect Loads
- Low-Latency Rolling-Window Analytics for Food Delivery
- Modeling an In-Memory File Tree Supporting mkdir and ls
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Optimal Ride-Share Group Size