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 riders is empty, return 0.

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 == [] returns 0).
  • len(riders[i]) == 2 and 1 <= riders[i][0] <= riders[i][1] <= 100,000.

Step-by-step walkthrough

  1. 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 size k satisfies min_size <= k <= max_size (both endpoints included). We want the integer k covered by the most riders, and if multiple sizes tie, the smallest such k (or 0 if riders is empty).

    Notice from Example 1 that k does not have to equal the number of eligible riders found — at k = 6, Example 1 still counts 2 eligible 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 3
    
  2. Why checking every size for every rider is too slow

    A direct brute-force loop checks every candidate size k from 1 up to M (the largest max_size, up to 100,000) and scans all n riders (n <= 100,000) to count how many intervals contain k.

    At n = 100,000 and M = 100,000, n * M reaches 10,000,000,000 (10^10) checks — far too slow. The wasted effort comes from recounting the same rider thousands of times across neighboring sizes: when k steps from k - 1 to k, the count only changes for riders who just joined at k or just dropped out after k - 1.

  3. Key idea: Record start and end changes in a difference array

    Instead of adding 1 to every slot inside [min_size, max_size], we keep a difference array diff where diff[k] records only how much the count changes when moving from k - 1 to k:

    • 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 diff is linear, recording n riders is just adding each rider's +1 and -1 into the same diff array (2 array updates per rider), and one running sum (prefix sum) from 1 upward recovers the combined count at every size!

  4. Build the difference array safely

    How long does diff need to be? If the largest max_size in the input is max_possible_size, that rider writes -1 to index max_possible_size + 1. Since Python lists are 0-indexed from 0 through len(diff) - 1, we allocate max_possible_size + 2 zeros so index max_possible_size + 1 is always valid (at most 100,002 ints).

        # 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
    
  5. Sweep left to right and break ties toward the smallest size

    Now we scan size from 1 to max_possible_size, adding diff[size] into eligible_riders at each step.

    To handle ties ("return the smallest such k"), we update best_size only when eligible_riders > best_count (strictly greater, not >=). Any later size that merely ties best_count is ignored, preserving the earliest (smallest) size that 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_size
    
  6. Trace Example 1 step by step

    Let's trace riders = [[3, 6], [1, 4], [4, 7], [2, 3]]:

    1. max_possible_size = 7, so diff starts with 9 zeros (indices 0..8).
    2. 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 +1 at index 4!)
    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 = 3
    

    The function returns 3.

  7. 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 the n riders once to find M, scan the n riders a second time doing two O(1) array updates per rider, and sweep across the M candidate group sizes once doing O(1) addition and comparison per size.
  • Space: O(M). We allocate one diff list of M + 2 integers (at most 100,002 elements) plus a handful of scalar tracking variables.

Edge cases

  • Empty list (riders = []): Handled explicitly at the top and returns 0 as specified in the problem statement.
  • Single rider ([[7, 9]]): Counts are 1 on 7..9; strict > locks in the first size 7.
  • Touching inclusive endpoints ([[1, 3], [3, 5]]): Because the first rider subtracts -1 at 3 + 1 = 4 rather than 3, both riders count at size 3, returning 3.
  • Ties in arbitrary input order ([[5, 5], [5, 5], [1, 1], [1, 1]]): Sweeping sizes in ascending order 1..M ensures 1 is visited before 5, returning 1 regardless of rider list ordering.
  • Disjoint unsorted intervals ([[10, 12], [3, 4], [7, 8]]): Every covered size has count 1, and the ascending sweep picks the smallest start 3.
  • Maximum boundary (max_size = 100,000): Writes -1 to diff[100001], which stays safely inside diff of length M + 2 = 100,002.

Common mistakes

  • Decrementing diff[max_size] instead of diff[max_size + 1]: Treats intervals as half-open [min_size, max_size), dropping every rider one size too early (so [[1, 3], [3, 5]] returns 1 instead of 3).
  • Allocating M + 1 slots instead of M + 2: Raises an IndexError as soon as the rider with max_size == M writes to diff[M + 1].
  • Using >= instead of > when updating best_count: Breaks ties in favor of the largest size instead of the smallest (returning 4 on Example 1 instead of 3).
  • Returning best_count instead of best_size: The caller asks for the optimal group size k, 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 the 2n events by coordinate, and processes all events sharing the same coordinate together before comparing the active count against best_count. For M <= 100,000, the O(n + M) difference array is faster and avoids sorting, while the event sweep shines when coordinates can be huge (such as 10^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-element diff list 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 all 2n events in O(n log n) time (O(n) space), sum all deltas at each distinct coordinate before checking eligible_riders > best_count, and return the winning coordinate. Because the rider count can only increase at an interval start min_size, the optimal smallest k is 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 same diff and prefix sums, then restrict the winner check eligible_riders > best_count to vip_min <= size <= vip_max (returning 0 if no valid size exists). If including them is a tie-breaker after maximizing rider count (most riders first, then priority rider included, then smallest size), compare the tuple (eligible_riders, vip_min <= size <= vip_max) with strict > as size increases from 1 to M, keeping O(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 +1 and -1 with +weight[i] and -weight[i]: set diff[min_size] += weight and diff[max_size + 1] -= weight. The prefix sum at size then equals the exact total payout of all riders eligible at size, and the same strict > scan finds the smallest k achieving the maximum total payout in O(n + M) time and O(M) space.

Follow-up questions

Similar questions

More Uber interview questions

All 217 Uber questions →