Optimal Ride-Share Group Size
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
A ride-sharing scheduler collects headcount preferences from n commuters. Commuter i provides a two-element list [low, high], indicating they are willing to join a shared vehicle whenever the chosen group headcount k satisfies low <= k <= high (both endpoints inclusive).
Implement find_optimal_group_size:
def find_optimal_group_size(riders: List[List[int]]) -> int:
Choose an integer headcount k (1 <= k <= 100,000) that lies within the preference range of as many commuters in riders as possible. Note that k represents a candidate headcount setting and does not need to equal the count of matching commuters.
- If several headcounts tie for the highest number of matching commuters, return the smallest such
k. - If
ridersis empty, return0.
Examples
Example 1
Input: riders = [[3, 6], [1, 4], [4, 7], [2, 3]]
Output: 3
Explanation:
- k = 1: matches [1, 4] (1 commuter).
- k = 2: matches [1, 4] and [2, 3] (2 commuters).
- k = 3: matches [3, 6], [1, 4], and [2, 3] (3 commuters).
- k = 4: matches [3, 6], [1, 4], and [4, 7] (3 commuters).
- k = 5, 6: match [3, 6] and [4, 7] (2 commuters each).
- k = 7: matches [4, 7] (1 commuter).
Both k = 3 and k = 4 match the peak of 3 commuters; tie-breaking picks the smaller value 3.
Example 2
Input: riders = [[6, 8], [2, 3], [9, 10]]
Output: 2
Explanation: Because the three intervals do not overlap, no headcount matches more than 1 commuter. Among all headcounts achieving 1 match (2, 3, 6, 7, 8, 9, 10), 2 is the smallest.
Example 3
Input: riders = [[2, 50000], [10, 80000], [25000, 25000]]
Output: 25000
Explanation: Headcount 25000 is the single integer contained in all three intervals (3 commuters), whereas every other size matches at most 2.
Constraints
0 <= len(riders) <= 100,000(riders == []returns0).len(riders[i]) == 2and1 <= riders[i][0] <= riders[i][1] <= 100,000.
Step-by-step walkthrough
Understand the problem as overlapping intervals
Each rider gives an acceptable range
[min_size, max_size], meaning they are willing to ride if the group sizeksatisfiesmin_size <= k <= max_size(both endpoints included). We want the integerkcovered by the most riders, and if multiple sizes tie, the smallest suchk(or0ifridersis empty).Notice from Example 1 that
kdoes not have to equal the number of eligible riders found — atk = 6, Example 1 still counts2eligible riders. So every rider is simply a closed interval[min_size, max_size]on a number line, and we want the leftmost integer covered by the highest stack of intervals:Example 1: riders = [[3, 6], [1, 4], [4, 7], [2, 3]] group size k: 1 2 3 4 5 6 7 rider 1 [3, 6]: [=================] rider 2 [1, 4]: [=================] rider 3 [4, 7]: [=================] rider 4 [2, 3]: [=====] ------------------------------------------------------- overlap count: 1 2 3 3 2 2 1 ^ smallest k reaching max count 3 -> return 3Why checking every size for every rider is too slow
A direct brute-force loop checks every candidate size
kfrom1up toM(the largestmax_size, up to100,000) and scans allnriders (n <= 100,000) to count how many intervals containk.At
n = 100,000andM = 100,000,n * Mreaches10,000,000,000(10^10) checks — far too slow. The wasted effort comes from recounting the same rider thousands of times across neighboring sizes: whenksteps fromk - 1tok, the count only changes for riders who just joined atkor just dropped out afterk - 1.Key idea: Record start and end changes in a difference array
Instead of adding
1to every slot inside[min_size, max_size], we keep a difference arraydiffwherediff[k]records only how much the count changes when moving fromk - 1tok:- At
min_size, this rider becomes eligible:diff[min_size] += 1. - Through
max_size, this rider stays eligible (so nothing changes yet!). - At
max_size + 1, this rider is no longer eligible:diff[max_size + 1] -= 1.
One rider with [3, 6]: index k: 0 1 2 3 4 5 6 7 8 diff[k]: 0 0 0 +1 0 0 0 -1 0 running sum: 0 0 0 1 1 1 1 0 0 ^--------------^ rider is counted on 3, 4, 5, 6!Because
diffis linear, recordingnriders is just adding each rider's+1and-1into the samediffarray (2array updates per rider), and one running sum (prefix sum) from1upward recovers the combined count at every size!- At
Build the difference array safely
How long does
diffneed to be? If the largestmax_sizein the input ismax_possible_size, that rider writes-1to indexmax_possible_size + 1. Since Python lists are0-indexed from0throughlen(diff) - 1, we allocatemax_possible_size + 2zeros so indexmax_possible_size + 1is always valid (at most100,002ints).# Edge case specified by the problem: an empty rider list returns 0. if not riders: return 0 # Phase 1: find the largest max_size so we only allocate as many slots as needed. max_possible_size = 0 for min_size, max_size in riders: if max_size > max_possible_size: max_possible_size = max_size # Phase 2: build the difference array. # diff[k]: net change in eligible riders when moving from group size k - 1 to k. # Allocate max_possible_size + 2 slots so index (max_possible_size + 1) is in bounds. diff = [0] * (max_possible_size + 2) for min_size, max_size in riders: diff[min_size] += 1 # Subtract at max_size + 1 because max_size itself is still an accepted size. diff[max_size + 1] -= 1Sweep left to right and break ties toward the smallest size
Now we scan
sizefrom1tomax_possible_size, addingdiff[size]intoeligible_ridersat each step.To handle ties ("return the smallest such
k"), we updatebest_sizeonly wheneligible_riders > best_count(strictly greater, not>=). Any later size that merely tiesbest_countis ignored, preserving the earliest (smallest)sizethat achieved that peak.# Phase 3: accumulate the prefix sum to recover the exact rider count at each size k. best_size = 0 best_count = 0 eligible_riders = 0 for size in range(1, max_possible_size + 1): eligible_riders += diff[size] # Strict '>' keeps the first (smallest) size whenever later sizes tie best_count. if eligible_riders > best_count: best_count = eligible_riders best_size = size return best_sizeTrace Example 1 step by step
Let's trace
riders = [[3, 6], [1, 4], [4, 7], [2, 3]]:max_possible_size = 7, sodiffstarts with9zeros (indices0..8).- Apply riders:
[3, 6]:diff[3] += 1,diff[7] -= 1[1, 4]:diff[1] += 1,diff[5] -= 1[4, 7]:diff[4] += 1,diff[8] -= 1[2, 3]:diff[2] += 1,diff[4] -= 1(cancels the+1at index4!)
index k: 0 1 2 3 4 5 6 7 8 diff[k]: 0 +1 +1 +1 0 -1 0 -1 -1 Sweep size = 1..7: size = 1: eligible = 0 + (+1) = 1 > 0 -> best_count = 1, best_size = 1 size = 2: eligible = 1 + (+1) = 2 > 1 -> best_count = 2, best_size = 2 size = 3: eligible = 2 + (+1) = 3 > 2 -> best_count = 3, best_size = 3 size = 4: eligible = 3 + 0 = 3 == 3 -> tie, keep best_size = 3 size = 5: eligible = 3 + (-1) = 2 < 3 -> keep best_size = 3 size = 6: eligible = 2 + 0 = 2 < 3 -> keep best_size = 3 size = 7: eligible = 2 + (-1) = 1 < 3 -> keep best_size = 3The function returns
3.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def find_optimal_group_size(riders: List[List[int]]) -> int: # Edge case specified by the problem: an empty rider list returns 0. if not riders: return 0 # Phase 1: find the largest max_size so we only allocate as many slots as needed. max_possible_size = 0 for min_size, max_size in riders: if max_size > max_possible_size: max_possible_size = max_size # Phase 2: build the difference array. # diff[k]: net change in eligible riders when moving from group size k - 1 to k. # Allocate max_possible_size + 2 slots so index (max_possible_size + 1) is in bounds. diff = [0] * (max_possible_size + 2) for min_size, max_size in riders: diff[min_size] += 1 # Subtract at max_size + 1 because max_size itself is still an accepted size. diff[max_size + 1] -= 1 # Phase 3: accumulate the prefix sum to recover the exact rider count at each size k. best_size = 0 best_count = 0 eligible_riders = 0 for size in range(1, max_possible_size + 1): eligible_riders += diff[size] # Strict '>' keeps the first (smallest) size whenever later sizes tie best_count. if eligible_riders > best_count: best_count = eligible_riders best_size = size return best_size✅ Submit now — all tests should pass.
Intuition & how it works
Imagine counting how many visitors are inside a museum during each minute of the day without stopping every minute to poll all 100,000 ticket holders. Instead, you place a clicker sheet at the doorway: whenever a visitor's ticket starts at min_size, you mark +1 at min_size, and because their ticket stays valid through max_size, you mark -1 at max_size + 1 right after they leave. That doorway log is a difference array (an array storing the net change from each position to the next rather than full counts), and walking through it from size 1 upward while keeping a prefix sum (a running total from the start up to the current index) reconstructs the exact number of eligible riders at every group size k.
A naive loop that tests every candidate group size k from 1 to 100,000 against all n = 100,000 riders performs up to 100,000 * 100,000 = 10^10 comparisons, which takes many seconds instead of milliseconds. Worse, almost all of those checks are redundant: a rider who accepts [1, 100000] gets checked 100,000 separate times, whereas the difference array records them in just two O(1) updates (diff[1] += 1 and diff[100001] -= 1).
Walk through Example 1 (riders = [[3, 6], [1, 4], [4, 7], [2, 3]]):
- Marking +1 at each min_size and -1 at each max_size + 1 produces diff[1..8] = [+1, +1, +1, 0, -1, 0, -1, -1] (at index 4, rider 3's +1 and rider 4's -1 cancel out to 0).
- Adding diff left to right gives running counts [1, 2, 3, 3, 2, 2, 1] for sizes 1..7.
- Because we only update best_size on a strict > improvement, size 3 wins (count = 3) and the tie at size 4 does not overwrite it, returning 3.
Complexity
Let n be the number of riders (len(riders)) and M be the largest max_size in the input (M <= 100,000).
- Time:
O(n + M). We scan thenriders once to findM, scan thenriders a second time doing twoO(1)array updates per rider, and sweep across theMcandidate group sizes once doingO(1)addition and comparison per size. - Space:
O(M). We allocate onedifflist ofM + 2integers (at most100,002elements) plus a handful of scalar tracking variables.
Edge cases
- Empty list (
riders = []): Handled explicitly at the top and returns0as specified in the problem statement. - Single rider (
[[7, 9]]): Counts are1on7..9; strict>locks in the first size7. - Touching inclusive endpoints (
[[1, 3], [3, 5]]): Because the first rider subtracts-1at3 + 1 = 4rather than3, both riders count at size3, returning3. - Ties in arbitrary input order (
[[5, 5], [5, 5], [1, 1], [1, 1]]): Sweeping sizes in ascending order1..Mensures1is visited before5, returning1regardless of rider list ordering. - Disjoint unsorted intervals (
[[10, 12], [3, 4], [7, 8]]): Every covered size has count1, and the ascending sweep picks the smallest start3. - Maximum boundary (
max_size = 100,000): Writes-1todiff[100001], which stays safely insidediffof lengthM + 2 = 100,002.
Common mistakes
- Decrementing
diff[max_size]instead ofdiff[max_size + 1]: Treats intervals as half-open[min_size, max_size), dropping every rider one size too early (so[[1, 3], [3, 5]]returns1instead of3). - Allocating
M + 1slots instead ofM + 2: Raises anIndexErroras soon as the rider withmax_size == Mwrites todiff[M + 1]. - Using
>=instead of>when updatingbest_count: Breaks ties in favor of the largest size instead of the smallest (returning4on Example 1 instead of3). - Returning
best_countinstead ofbest_size: The caller asks for the optimal group sizek, not how many riders fit it.
Alternative approaches
- Coordinate-compressed sweep-line (
O(n log n)time,O(n)space): A sweep-line algorithm converts each interval[low, high]into two coordinate events(low, +1)and(high + 1, -1), sorts the2nevents by coordinate, and processes all events sharing the same coordinate together before comparing the active count againstbest_count. ForM <= 100,000, theO(n + M)difference array is faster and avoids sorting, while the event sweep shines when coordinates can be huge (such as10^9).
Follow-up questions
- How would you adapt the algorithm if candidate group sizes could reach 10^9 while the rider count stays at most 100,000? Allocating a
10^9-elementdifflist would exhaust gigabytes of memory and time out, so switch to the sorted event sweep-line: emit(min_size, +1)and(max_size + 1, -1)for each rider, sort all2nevents inO(n log n)time (O(n)space), sum all deltas at each distinct coordinate before checkingeligible_riders > best_count, and return the winning coordinate. Because the rider count can only increase at an interval startmin_size, the optimal smallestkis guaranteed to be one of the event coordinates visited by the sweep. - Suppose a designated priority rider is given—how would you incorporate either requiring their participation or using their inclusion to break ties before choosing the smallest size? If including the priority rider (
[vip_min, vip_max]) is a hard requirement, build the exact samediffand prefix sums, then restrict the winner checkeligible_riders > best_counttovip_min <= size <= vip_max(returning0if no valid size exists). If including them is a tie-breaker after maximizing rider count (most riders first, then priority rider included, then smallestsize), compare the tuple(eligible_riders, vip_min <= size <= vip_max)with strict>assizeincreases from1toM, keepingO(n + M)time. - If each rider carries a positive payout weight and the goal shifts to maximizing total payout instead of headcount, what changes in your implementation? Replace
+1and-1with+weight[i]and-weight[i]: setdiff[min_size] += weightanddiff[max_size + 1] -= weight. The prefix sum atsizethen equals the exact total payout of all riders eligible atsize, and the same strict>scan finds the smallestkachieving the maximum total payout inO(n + M)time andO(M)space.
Follow-up questions
- How would you adapt the algorithm if candidate group sizes could reach 10^9 while the rider count stays at most 100,000?
- Suppose a designated priority rider is given—how would you incorporate either requiring their participation or using their inclusion to break ties before choosing the smallest size?
- If each rider carries a positive payout weight and the goal shifts to maximizing total payout instead of headcount, what changes in your implementation?
Similar questions
- Aggregate Category Sales Metrics
- Repeated Uphill Shortest-Path Grid Queries
- Deterministic Room Allocation for Intervals
- Leftmost Longest Pattern Replacement
- Quadtree Compression and Safe Graph Nodes
- Quadtree Compression and 8-Neighbor Grid Word Search
More Uber interview questions
- Multi-Level Parking Garage Medium
- Deterministic Room Allocation for Intervals Medium
- Walk Through Your Highest-Impact Engineering Project Medium Pro
- Balanced Prefix Ranges of a Permutation Medium Pro
- First Timestamp Uniting All Target Users Medium Pro
- Locate Grid Robots by Directional Clearances Hard Pro
- Smallest Larger Palindromic Integer Medium Pro
- Locate Grid Robots by Four-Way Obstacle Distances Medium Pro
- Final Exiting Truck on a Single-Track Road Medium Pro
- Highest Path Sum Using Prime-Length Leaps Hard Pro