Eddington Number of Daily Rides

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

A cycling journal stores one positive integer per logged ride in distances, where distances[i] gives the mileage ridden during outing i.

A cyclist's Eddington number E is defined as the greatest integer E for which the journal contains at least E outings with mileage greater than or equal to E (distances[i] >= E).

Implement compute_eddington_number(distances) to return E.

Note that E does not need to equal any value present in distances, and E can never exceed len(distances) because there are only len(distances) logged outings in total.

Examples

Example 1

distances = [2, 9, 4, 4, 7, 1]

Output: 4

Explanation: Four outings (9, 7, 4, and 4) each cover at least 4 miles, so E = 4 holds. Testing 5 fails because only two outings (9 and 7) cover 5 or more miles.

Example 2

distances = [12, 15, 6, 3, 2]

Output: 3

Explanation: Four outings (15, 12, 6, and 3) have mileage >= 3, which easily clears the 3-outing requirement. Only three outings (15, 12, and 6) reach >= 4, falling one outing short of E = 4.

Example 3

distances = [25, 40]

Output: 2

Explanation: Although both rides are much longer than 2, only 2 outings exist in total, capping E at 2.

Constraints

  • 1 <= len(distances) <= 2 * 10^5
  • 1 <= distances[i] <= 10^9

Step-by-step walkthrough

  1. Understand the goal and its bounds

    We receive distances, a list of n positive integers (1 <= n <= 200,000) recording the mileage of each cycling outing. We want the Eddington number E: the largest whole number such that at least E outings achieved a mileage of E or higher.

    Before writing any code, two observations pin down the possible range of E:

    • E is at least 1: there is at least one outing, and every outing has mileage >= 1, so at least 1 outing satisfies >= 1.
    • E is at most n: you cannot have more qualifying outings than total outings logged. In Example 3 (distances = [25, 40]), there are only 2 outings total, so E = 2 (not 25).

    So E is always an integer between 1 and n.

  2. Brute force: test every candidate E

    Since E must be between 1 and n, the most direct approach tries e = n, n - 1, ..., 1. For each candidate e, we scan the list and count how many rides have distance >= e. Because we count downward from n, the first e with at least e qualifying outings is the largest valid answer:

    def eddington_brute(distances):
        for e in range(len(distances), 0, -1):
            qualifying_days = 0
            for d in distances:
                if d >= e:
                    qualifying_days += 1
            if qualifying_days >= e:
                return e
        return 0
    

    Why is this too slow? Each candidate e scans all n outings, giving O(n^2) comparisons in the worst case. When n = 200,000, n^2 reaches 40,000,000,000 operations, which will time out. We need a way to test candidate k in O(1) time instead of rescanning the list.

  3. Key idea: sort from longest ride to shortest

    Suppose we sort the rides in descending order into longest_first. Now the k longest rides sit right at the front in longest_first[0 .. k-1], and the shortest ride among those top k outings sits at index k - 1.

    Spot k (days = i + 1):     1    2    3    4    5    6
    Index i:                   0    1    2    3    4    5
    longest_first:           [ 9,   7,   4,   4,   2,   1]
                               ^              ^    ^
                               longest    4 >= 4   2 < 5 (too short!)
                               |---- 4 days >= 4 --|
    

    Ask: "Are there at least k outings with mileage >= k?"

    • If longest_first[k - 1] >= k: every ride to the left (0 .. k-1) is at least as long as longest_first[k - 1], so all k rides in that prefix have mileage >= k. The answer is yes.
    • If longest_first[k - 1] < k: every ride from index k - 1 onward is < k, leaving at most k - 1 rides before it that could be >= k. Fewer than k outings qualify, so the answer is no.

    Sorting once lets us check any candidate k with a single comparison!

  4. Why we can stop at the first failure

    As we move from left to right (i = 0, 1, 2, ...):

    • days = i + 1 strictly increases (1, 2, 3, 4, ...).
    • longest_first[i] decreases or stays the same because the list is sorted high-to-low.

    Once longest_first[i] < days happens for the first time, every later position has an even larger days requirement and an equal-or-smaller ride distance. So no later position can ever pass again. We simply remember the last days value that passed and break on the first failure.

  5. Write the scan

    Using sorted(distances, reverse=True) builds a new sorted copy so we do not mutate the caller's input list. Notice we check shortest_in_prefix >= days (not >), because a ride of distance 4 counts toward E = 4.

        # Phase 1: sort ride distances from longest to shortest (leaves caller's list unchanged).
        # longest_first: descending list of ints, e.g. [9, 7, 4, 4, 2, 1].
        longest_first = sorted(distances, reverse=True)
    
        # eddington: largest day count k seen so far where the top k rides are all >= k.
        eddington = 0
    
        # Phase 2: check prefixes of size 1, 2, ..., n in order.
        for i in range(len(longest_first)):
            # Prefix longest_first[0..i] contains `days` rides, and longest_first[i] is the shortest among them.
            days = i + 1
            shortest_in_prefix = longest_first[i]
    
            # Use >= because a ride of distance exactly E still counts toward E.
            if shortest_in_prefix >= days:
                eddington = days
            else:
                # Stop early: `days` only grows while `longest_first[i]` only shrinks or stays equal,
                # so no larger prefix can ever satisfy shortest_in_prefix >= days.
                break
    
        return eddington
    
  6. Trace the examples step by step

    Let's trace Example 1 ([2, 9, 4, 4, 7, 1]) and Example 2 ([12, 15, 6, 3, 2]):

    Example 1: distances = [2, 9, 4, 4, 7, 1]
    Sorted descending -> longest_first = [9, 7, 4, 4, 2, 1]
    
      i=0: days=1, shortest_in_prefix=9  ->  9 >= 1 (pass) -> eddington = 1
      i=1: days=2, shortest_in_prefix=7  ->  7 >= 2 (pass) -> eddington = 2
      i=2: days=3, shortest_in_prefix=4  ->  4 >= 3 (pass) -> eddington = 3
      i=3: days=4, shortest_in_prefix=4  ->  4 >= 4 (pass) -> eddington = 4
      i=4: days=5, shortest_in_prefix=2  ->  2 <  5 (fail) -> break! Return 4.
    
    Example 2: distances = [12, 15, 6, 3, 2]
    Sorted descending -> longest_first = [15, 12, 6, 3, 2]
    
      i=0: days=1, shortest_in_prefix=15 -> 15 >= 1 (pass) -> eddington = 1
      i=1: days=2, shortest_in_prefix=12 -> 12 >= 2 (pass) -> eddington = 2
      i=2: days=3, shortest_in_prefix=6  ->  6 >= 3 (pass) -> eddington = 3
      i=3: days=4, shortest_in_prefix=3  ->  3 <  4 (fail) -> break! Return 3.
    

    In Example 3 ([25, 40]), longest_first = [40, 25]: both i = 0 (40 >= 1) and i = 1 (25 >= 2) pass, and the loop finishes cleanly and returns 2.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def compute_eddington_number(distances: List[int]) -> int:
        # Phase 1: sort ride distances from longest to shortest (leaves caller's list unchanged).
        # longest_first: descending list of ints, e.g. [9, 7, 4, 4, 2, 1].
        longest_first = sorted(distances, reverse=True)
    
        # eddington: largest day count k seen so far where the top k rides are all >= k.
        eddington = 0
    
        # Phase 2: check prefixes of size 1, 2, ..., n in order.
        for i in range(len(longest_first)):
            # Prefix longest_first[0..i] contains `days` rides, and longest_first[i] is the shortest among them.
            days = i + 1
            shortest_in_prefix = longest_first[i]
    
            # Use >= because a ride of distance exactly E still counts toward E.
            if shortest_in_prefix >= days:
                eddington = days
            else:
                # Stop early: `days` only grows while `longest_first[i]` only shrinks or stays equal,
                # so no larger prefix can ever satisfy shortest_in_prefix >= days.
                break
    
        return eddington
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine printing each bike ride as a vertical bar, lining the bars up from tallest to shortest in spots numbered 1, 2, 3, ..., and trying to tuck the largest possible E x E square underneath them against the left wall. That side length E is the Eddington number (the exact same threshold rule as a researcher's h-index, which is the largest number h such that h published papers each have at least h citations). Because the rides are ordered from longest to shortest, checking whether the top k rides all have mileage >= k only requires checking the shortest of those k rides — the one standing in spot k.

The obvious approach is to test every candidate E from n down to 1 and scan the whole list to count how many outings have distance >= E. That fails on large logs because rescanning all n outings for up to n candidates takes O(n^2) comparisons — up to 40 billion checks when n = 200,000. Sorting once eliminates all that repeated counting.

Walk through Example 1 (distances = [2, 9, 4, 4, 7, 1], 6 outings): 1. Sort from longest to shortest: [9, 7, 4, 4, 2, 1]. 2. Spot 1 (i = 0): shortest of the top 1 ride is 9 >= 1, so E = 1 works. 3. Spot 2 (i = 1): shortest of the top 2 rides is 7 >= 2, so E = 2 works. 4. Spot 3 (i = 2): shortest of the top 3 rides is 4 >= 3, so E = 3 works. 5. Spot 4 (i = 3): shortest of the top 4 rides is 4 >= 4, so E = 4 works. 6. Spot 5 (i = 4): shortest of the top 5 rides is 2 < 5, so we stop and return 4.

Complexity

  • Time: O(n log n), where n is len(distances). Sorting the n ride distances takes O(n log n) comparisons, and the single left-to-right pass afterward inspects each element at most once in O(n) time, so sorting dominates.
  • Space: O(n) because sorted(distances, reverse=True) allocates a new list of n integers. If modifying the caller's list in place were allowed, distances.sort(reverse=True) would avoid the full copy.

Edge cases

  • Single outing ([1] or [10^9]): returns 1, because 1 outing has mileage >= 1 and there is no second outing.
  • Capped by outing count ([25, 40]): returns 2, because E can never exceed len(distances).
  • Exact boundary ties ([4, 4, 4, 4]): returns 4, because a ride with mileage equal to E satisfies >= E.
  • All unit-length rides ([1, 1, 1, 1]): returns 1, since spot 2 immediately fails (1 < 2).
  • Duplicates and arbitrary order ([2, 9, 4, 4, 7, 1]): returns 4, because only the multiset of ride lengths matters, not their chronological order.

Common mistakes

  • Using > instead of >=: rejects exact-match outings, turning [4, 4, 4, 4] into 3 instead of 4.
  • Returning longest_first[i] instead of i + 1: returns a mileage value instead of an outing count; on [25, 40] the answer is 2, not 25.
  • Assuming E must appear in distances: [25, 40] has E = 2 even though 2 is not in the input, so only testing values from distances misses the right answer.
  • Off-by-one indexing (longest_first[i] >= i): forgets that 0-based index i represents i + 1 outings, falsely accepting E = 2 on [1, 1, 1, 1].
  • Sorting ascending without flipping the index: in ascending order [1, 2, 4, 4, 7, 9], the k longest rides are at the end (ascending[n - k] >= k), so testing ascending[k - 1] >= k checks the k-th shortest ride instead.

Alternative approaches

  • Bucket counting in O(n) time and O(n) space: Bucket counting (a simplified form of counting sort that tallies how many items fall into each integer slot) avoids sorting altogether. Because E can never exceed n, any ride longer than n plays the exact same role as a ride of length n. We create n + 1 buckets (0 .. n), clamp every ride d to min(d, n), and then accumulate counts from n down to 1 until the running total of rides >= e reaches e:
def eddington_counting(distances):
    n = len(distances)
    # count[k]: number of outings with mileage k (rides > n are capped into bucket n)
    count = [0] * (n + 1)
    for d in distances:
        count[min(d, n)] += 1

    days_at_least_e = 0
    for e in range(n, 0, -1):
        days_at_least_e += count[e]
        if days_at_least_e >= e:
            return e
    return 0
  • Binary search on the answer in O(n log n) time and O(1) space: Binary search repeatedly halves a search range [1, n] when a yes/no condition flips cleanly from True to False at one threshold. Checking a midpoint mid scans distances in O(n) time over O(log n) halving steps, matching O(n log n) time without extra memory or modifying the input.

Follow-up questions

  • How can you compute the Eddington number in O(n) linear time without sorting? Use the bucket-counting approach above. Even though individual distances can be up to 10^9, the Eddington number cannot exceed n, so clamping every distance d to min(d, n) collapses the range into n + 1 buckets. One pass fills the buckets and one backward pass accumulates how many outings are >= e, taking O(n) time and O(n) space.
  • If new ride distances arrive one at a time in an online stream, how can you maintain the current Eddington number in amortized O(1) time per ride? Maintain the current E, a dictionary count_at storing ride counts only for integer distances strictly above E, and an integer rides_above counting all rides strictly longer than E. Because distances are whole numbers, d > E is identical to d >= E + 1, and a single new ride can raise E by at most 1: whenever rides_above reaches E + 1, increment E by 1 and subtract count_at.pop(E, 0) from rides_above because rides equal to the new E are no longer strictly above it. Each ride performs a constant number of dictionary lookups, running in amortized O(1) time (meaning constant time per operation averaged over a sequence of updates).

```python class EddingtonTracker: def init(self): self.eddington = 0 self.rides_above = 0 # count of rides with distance > self.eddington self.count_at = {} # distance -> ride count for distances > self.eddington

  def add_ride(self, d: int) -> int:
      if d > self.eddington:
          self.rides_above += 1
          self.count_at[d] = self.count_at.get(d, 0) + 1
      if self.rides_above > self.eddington:
          self.eddington += 1
          self.rides_above -= self.count_at.pop(self.eddington, 0)
      return self.eddington

```

  • Given a rider's current log, how would you determine the minimum number of additional rides needed to reach E + 1? Count how many existing outings already have distance >= E + 1, and call that count c. Because reaching E + 1 requires E + 1 outings of mileage at least E + 1 (and we know c <= E), the rider needs exactly (E + 1) - c additional rides of length >= E + 1. You can find c in a single O(n) scan of distances.

Follow-up questions

Similar questions

More Liftoff interview questions

All 6 Liftoff questions →