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^51 <= distances[i] <= 10^9
Step-by-step walkthrough
Understand the goal and its bounds
We receive
distances, a list ofnpositive integers (1 <= n <= 200,000) recording the mileage of each cycling outing. We want the Eddington numberE: the largest whole number such that at leastEoutings achieved a mileage ofEor higher.Before writing any code, two observations pin down the possible range of
E:Eis at least1: there is at least one outing, and every outing has mileage>= 1, so at least1outing satisfies>= 1.Eis at mostn: you cannot have more qualifying outings than total outings logged. In Example 3 (distances = [25, 40]), there are only2outings total, soE = 2(not25).
So
Eis always an integer between1andn.Brute force: test every candidate E
Since
Emust be between1andn, the most direct approach triese = n, n - 1, ..., 1. For each candidatee, we scan the list and count how many rides havedistance >= e. Because we count downward fromn, the firstewith at leastequalifying 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 0Why is this too slow? Each candidate
escans allnoutings, givingO(n^2)comparisons in the worst case. Whenn = 200,000,n^2reaches40,000,000,000operations, which will time out. We need a way to test candidatekinO(1)time instead of rescanning the list.Key idea: sort from longest ride to shortest
Suppose we sort the rides in descending order into
longest_first. Now theklongest rides sit right at the front inlongest_first[0 .. k-1], and the shortest ride among those topkoutings sits at indexk - 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
koutings with mileage>= k?"- If
longest_first[k - 1] >= k: every ride to the left (0 .. k-1) is at least as long aslongest_first[k - 1], so allkrides in that prefix have mileage>= k. The answer is yes. - If
longest_first[k - 1] < k: every ride from indexk - 1onward is< k, leaving at mostk - 1rides before it that could be>= k. Fewer thankoutings qualify, so the answer is no.
Sorting once lets us check any candidate
kwith a single comparison!- If
Why we can stop at the first failure
As we move from left to right (
i = 0, 1, 2, ...):days = i + 1strictly 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] < dayshappens for the first time, every later position has an even largerdaysrequirement and an equal-or-smaller ride distance. So no later position can ever pass again. We simply remember the lastdaysvalue that passed andbreakon the first failure.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 checkshortest_in_prefix >= days(not>), because a ride of distance4counts towardE = 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 eddingtonTrace 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]: bothi = 0(40 >= 1) andi = 1(25 >= 2) pass, and the loop finishes cleanly and returns2.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
nislen(distances). Sorting thenride distances takesO(n log n)comparisons, and the single left-to-right pass afterward inspects each element at most once inO(n)time, so sorting dominates. - Space: O(n) because
sorted(distances, reverse=True)allocates a new list ofnintegers. 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]): returns1, because 1 outing has mileage>= 1and there is no second outing. - Capped by outing count (
[25, 40]): returns2, becauseEcan never exceedlen(distances). - Exact boundary ties (
[4, 4, 4, 4]): returns4, because a ride with mileage equal toEsatisfies>= E. - All unit-length rides (
[1, 1, 1, 1]): returns1, since spot 2 immediately fails (1 < 2). - Duplicates and arbitrary order (
[2, 9, 4, 4, 7, 1]): returns4, 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]into3instead of4. - Returning
longest_first[i]instead ofi + 1: returns a mileage value instead of an outing count; on[25, 40]the answer is2, not25. - Assuming
Emust appear indistances:[25, 40]hasE = 2even though2is not in the input, so only testing values fromdistancesmisses the right answer. - Off-by-one indexing (
longest_first[i] >= i): forgets that 0-based indexirepresentsi + 1outings, falsely acceptingE = 2on[1, 1, 1, 1]. - Sorting ascending without flipping the index: in ascending order
[1, 2, 4, 4, 7, 9], theklongest rides are at the end (ascending[n - k] >= k), so testingascending[k - 1] >= kchecks thek-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
Ecan never exceedn, any ride longer thannplays the exact same role as a ride of lengthn. We createn + 1buckets (0 .. n), clamp every ridedtomin(d, n), and then accumulate counts fromndown to1until the running total of rides>= ereachese:
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 midpointmidscansdistancesinO(n)time overO(log n)halving steps, matchingO(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 exceedn, so clamping every distancedtomin(d, n)collapses the range inton + 1buckets. One pass fills the buckets and one backward pass accumulates how many outings are>= e, takingO(n)time andO(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 dictionarycount_atstoring ride counts only for integer distances strictly aboveE, and an integerrides_abovecounting all rides strictly longer thanE. Because distances are whole numbers,d > Eis identical tod >= E + 1, and a single new ride can raiseEby at most1: wheneverrides_abovereachesE + 1, incrementEby1and subtractcount_at.pop(E, 0)fromrides_abovebecause rides equal to the newEare 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 countc. Because reachingE + 1requiresE + 1outings of mileage at leastE + 1(and we knowc <= E), the rider needs exactly(E + 1) - cadditional rides of length>= E + 1. You can findcin a singleO(n)scan ofdistances.
Follow-up questions
- How can you compute the Eddington number in O(n) linear time without sorting?
- 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?
- Given a rider's current log, how would you determine the minimum number of additional rides needed to reach E + 1?
Similar questions
- Shortest Connection Degree in a Social Network
- Shortest Substring Run-Length Encoding and Decoding
- Validate and Expand an IPv6 Address
- Build a Terminal-Ready Tetris Engine
- Upper-Tail Probability of 1,000 Die Rolls
- 2D Max Pooling with Source Coordinates