Min deletions to avoid overlap in first k
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates array and sequence manipulation skills, set-based reasoning about value overlap, and the ability to compute minimal edits while preserving relative order constraints.
Constraints
- 1 <= k <= min(len(list1), len(list2))
- len(list1), len(list2) <= 2 * 10^5
- Array values may be negative and may contain duplicates
Examples
Input: ([1, 2, 3], [2, 1, 4, 5], 2)
Expected Output: 2
Explanation: The forbidden set is {1, 2}. In `list2`, the first two values must be deleted, then 4 and 5 become the first two remaining elements.
Input: ([1, 2, 3, 4], [2, 5, 3, 6], 2)
Expected Output: 1
Explanation: The forbidden set is {1, 2}. Delete 2, then 5 and 3 become the first two elements, and both are allowed.
Input: ([4, 5, 6], [7, 4, 8, 5], 2)
Expected Output: 1
Explanation: The forbidden set is {4, 5}. Keep 7, delete 4, keep 8. Now the first two remaining elements are 7 and 8. The last 5 may stay because it is after the first k elements.
Input: ([1, 2], [1, 2, 1], 2)
Expected Output: -1
Explanation: The forbidden set is {1, 2}. There are no valid elements available, so it is impossible to obtain 2 valid front elements.
Input: ([7, 7, 8], [7, 9, 7, 10, 11], 3)
Expected Output: 2
Explanation: The forbidden set is {7, 8}. Delete the two 7s before collecting 9, 10, and 11 as the first three remaining elements.
Input: ([1, 2, 3], [1], 0)
Expected Output: 0
Explanation: If k = 0, there is no requirement on the front of `list2`, so no deletions are needed.
Input: ([-1, 2], [-1, -2, 2, -3], 2)
Expected Output: 2
Explanation: The forbidden set is {-1, 2}. Delete -1 and 2, then -2 and -3 become the first two remaining elements.
Hints
- Only the part of `list2` before the k-th kept valid element can affect the answer. Once you have k valid front elements, everything after that can stay.
- Build a set from `list1[:k]`, then scan `list2` from left to right. Count valid elements you can keep and forbidden elements that must be deleted before you reach k valid ones.