Problem 367221 · medium · Level 03 Linear Management & Searching

The k-th Unclaimed Locker Number

binary search · arrays

A school's lockers are numbered 1, 2, 3, ... without end, and nums lists the numbers already taken, in strictly increasing order. New pupils are handed the free numbers from the smallest up. Return the number the k-th new pupil receives, which is the k-th positive integer not in nums.

Examples

Input:  nums = [1, 4, 5, 8], k = 4
Output: 7
Explanation: the free locker numbers are 2, 3, 6, 7, 9, 10, ...

Input:  nums = [1, 2, 3], k = 3
Output: 6

Input:  nums = [5], k = 3
Output: 3

Constraints

  • 0 <= len(nums) <= 10**6, 1 <= k <= 10**9
  • 1 <= nums[i] <= 10**9
  • Required time: O(log n); walking through the missing numbers is too slow.

Goals

  • Derive a monotone quantity (missing count before index i) from the array
  • Handle the answer lying beyond the last element
Starting Python…