KatInterview

K-th Missing Positive and Sliding-Window Duplicate Events

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingarrayssortingsliding-window

Last updated

Tests order-statistics reasoning for k-th missing positive integers and time-window frequency tracking to detect repeated log events.

You are given two independent tasks. Solve both and return their answers together as a two-element list.


Task 1: K-th Absent Positive Integer

You have an array nums of distinct positive integers and an integer k.

The absent positives are all positive integers that do not appear anywhere in nums — think of them as the gaps in the number line left by nums.

Return the k-th smallest absent positive integer.


Task 2: Repeated Events Inside a Time Window

You have two equal-length arrays, ops and times:

  • ops[i] is a string label for the i-th event (e.g. "login", "sync").
  • times[i] is the integer timestamp (in seconds) when that event occurred.

You are also given an integer window (in seconds).

An event at index i is flagged if there exist two earlier events j and k (in chronological order, j before k before i) such that:

  • All three share the same label: ops[j] == ops[k] == ops[i]
  • The three occurrences fit inside a window of size window: times[i] - times[j] <= window

Return the total count of flagged events.

Notes:

  • The input is not guaranteed to be sorted by time. Process events in ascending timestamp order.
  • When two events share the same timestamp, treat the one with the smaller original index as earlier.
  • A flagged event still counts as an occurrence for evaluating future events.

Return Value

Return a list of two integers: [answer_to_task1, answer_to_task2].


Constraints

  • 1 <= len(nums) <= 2 * 10^5
  • 1 <= nums[i] <= 10^9 (all values in nums are distinct)
  • 1 <= k <= 10^9
  • 1 <= len(ops) == len(times) <= 2 * 10^5
  • ops[i] consists of lowercase and uppercase English letters and digits
  • 0 <= times[i] <= 10^9
  • 0 <= window <= 10^9

Examples

Example 1

Input: solve_tasks([2, 3, 7, 11], 5, ['A', 'B', 'A', 'A', 'A'], [1, 2, 3, 4, 10], 5)

Output: [8, 1]

Example 2

Input: solve_tasks([4, 1, 8], 3, ['x', 'x', 'x'], [5, 1, 3], 2)

Output: [5, 0]

Hints

Hint 1

For Task 1, sort `nums` and think about how each value that lands at or below your current candidate answer pushes that candidate one step higher. You don't need to enumerate the missing numbers themselves.

Hint 2

For Task 1 an alternative is binary search: the number of absent positives up to position `m` in the sorted array is `m - (count of nums ≤ m)`. Find the smallest `m` where that count reaches `k`.

Hint 3

For Task 2, sort events by `(timestamp, original_index)` and keep only the two most recent timestamps per label. An event is flagged when the current timestamp minus the older of those two stored timestamps fits within `window`.