KatInterview

Largest Threshold Met by Daily Step Counts

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortingcountingh-index

Last updated

Find the largest integer k such that at least k entries in a list are at least k, testing sorting or counting-based selection and reasoning about monotone thresholds.

Largest Threshold Met by Daily Step Counts

A walker records how many kilometres they covered on each day of a long trip. You are given these records as a list of positive integers, daily_km, where daily_km[i] is the distance for day i. The days are in no particular order.

Define a milestone value m as follows: m is valid if at least m of the days have a distance of at least m.

Your task is to return the largest valid milestone value.

Details

  • A day counts toward m whenever its distance is greater than or equal to m; equal values are counted.
  • The same day may count toward the check for many different values of m.
  • The result can never exceed the number of days, since you cannot have more than n qualifying days.
  • Do not rely on the input being sorted. Avoid assumptions that break with duplicate values.

Function

Implement a function that takes the list daily_km and returns a single integer: the largest valid milestone value.

Constraints

  • 1 <= len(daily_km) <= 2 * 10^5
  • 1 <= daily_km[i] <= 10^9
  • Aim for a solution that runs comfortably within time limits for the largest input size.

Examples

Example 1

Input: largest_milestone([1, 3, 3, 5, 6])

Output: 3

Example 2

Input: largest_milestone([10, 8, 5, 4, 3])

Output: 4

Example 3

Input: largest_milestone([1, 1, 1])

Output: 1

Hints

Hint 1

Think of the days sorted from longest to shortest. If you look at the k-th longest day, what does its value tell you about whether k qualifying days exist?

Hint 2

At least k days are >= k exactly when the k-th largest value is >= k. Once this fails for some k, it fails for every larger k, so you can stop early.

Hint 3

For a linear-time variant: the answer is at most n, so clamp each value to n, count occurrences in buckets, and sweep k from n down to 1 with a running total of days with value >= k.