K-th Missing Positive and Sliding-Window Duplicate Events
Arrays & HashingAuto-graded · 17 test casesLast 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^51 <= nums[i] <= 10^9(all values innumsare distinct)1 <= k <= 10^91 <= len(ops) == len(times) <= 2 * 10^5ops[i]consists of lowercase and uppercase English letters and digits0 <= times[i] <= 10^90 <= 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`.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Task 1: K-th Absent Positive Integer
Core identity: for any integer m, the number of absent positives in [1, m] equals m minus the count of nums values that are ≤ m. Once the array is sorted that count is a bisect_right call, so the identity is cheap to evaluate.
Binary search on the answer directly. The search space is [1, k + len(nums)] because even in the worst case (nums = [1, 2, …, n]) the k-th absent positive is n + k, which sits within that range.
- If
missing(mid) >= k, the answer is atmidor to the left →hi = mid. - Otherwise the answer is strictly to the right →
lo = mid + 1.
The loop terminates with lo == hi pointing at the smallest m where the absent count first reaches k. That is the answer.
Why it is correct: the absent count is a non-decreasing step function of m, so binary search on it is valid. Distinctness guarantees each element in nums contributes exactly one occupied slot, so bisect_right counts correctly.
Complexity: O(n log n) to sort, O(log(n + k)) for the binary search — dominated by sorting.
Space: O(n) for the sorted copy (or O(1) extra if sorting in-place is acceptable).
Task 2: Repeated Events Inside a Time Window
First, impose a canonical ordering by sorting event indices by (timestamp, original_index). This handles unsorted input and resolves ties deterministically.
Then do a single pass. For each event label, maintain a deque of timestamps of recent occurrences. Before inspecting the current event, evict any timestamps from the front of the deque that are strictly older than current_time - window (they can no longer form a valid triple with the current event at the right end).
If after eviction the deque already holds 2 or more timestamps, the current event is flagged: those two timestamps are valid earlier occurrences j and k, and all three fit within window seconds. Increment the counter.
Always append the current timestamp to the deque afterwards — flagged events still count as occurrences.
Why two stored timestamps suffice as a mental model: the deque naturally holds all timestamps within the window, and len(queue) >= 2 is exactly the condition that at least two prior occurrences exist in the window. The deque approach generalises cleanly if the threshold were "4th occurrence" by just changing 2 to 3.
Why the greedy eviction is correct: any timestamp outside [current_time - window, current_time] cannot participate in a valid triple ending at the current event. Removing them does not affect future events either, because future events have timestamps ≥ current_time, so those old entries would be evicted then too.
Complexity: O(n log n) to sort, O(n) amortised for the pass (each timestamp is pushed and popped at most once per deque). String key lookups are O(label length) per event. Space is O(n) for the sorted index list and O(U) for the deque map, where U is the number of distinct labels.
Edge Cases
- All of
numslarger thank: binary search still works;missing(k) = ksince none of[1, k]is occupied. nums = [1, 2, …, n]: the answer isn + k; binary search reaches it naturally.- Fewer than 3 events for a label: that label never triggers a flag.
window = 0: three events of the same label at the exact same timestamp flag the third one (all fit in a zero-length window).- Empty
ops/times: the loop does not execute; the answer is 0.
from bisect import bisect_right
from collections import defaultdict, deque
from typing import List
def solve_tasks(nums: List[int], k: int, ops: List[str], times: List[int], window: int) -> List[int]:
# --- Task 1: K-th absent positive via binary search ---
ordered_nums = sorted(nums)
lo, hi = 1, k + len(ordered_nums)
while lo < hi:
mid = (lo + hi) // 2
# How many numbers from 1..mid are absent?
# = mid minus the count of nums values that are <= mid
missing = mid - bisect_right(ordered_nums, mid)
if missing >= k:
hi = mid
else:
lo = mid + 1
kth_missing = lo
# --- Task 2: Count flagged events via sliding window per label ---
# Sort events by (timestamp, original index) to respect tie-breaking rule
event_order = sorted(range(len(ops)), key=lambda i: (times[i], i))
recent = defaultdict(deque) # label -> deque of timestamps within the window
redundant = 0
for i in event_order:
t = times[i]
queue = recent[ops[i]]
# Drop timestamps that have fallen outside the window
while queue and queue[0] < t - window:
queue.popleft()
# If there are already 2 or more occurrences in the window, this one is flagged
if len(queue) >= 2:
redundant += 1
# Always record this event (flagged events still count as occurrences)
queue.append(t)
return [kth_missing, redundant]