Delete a Character From Cover
DatabricksMachine Learning Engineer · OnsiteLast updated
This problem tests your ability to manage dynamic string indices by maintaining a set of active intervals and adjusting them efficiently after a character deletion.
Problem: Interval-Aware Deletion
You are given a string of length N (initially indices 0 to N-1) and a list of intervals [start, end] (inclusive) representing protected segments of the string. You are also given a list of deletions, where each deletion specifies an index i to remove from the current string. When a character is deleted, the indices of all subsequent characters shift to the left by 1.
Your task is to implement a function that processes these deletions sequentially and returns the final state of the protected intervals. If a deletion index falls within an interval, the interval should be shortened or split accordingly. If the deletion index is outside any protected interval, simply shift the boundaries of the intervals that appear after the deleted index.
Function Signature
def update_intervals(n: int, intervals: List[List[int]], deletions: List[int]) -> List[List[int]]:
Constraints
n: up to 10^5- Number of intervals and deletions: up to 10^4
- The string index
iprovided indeletionsrefers to the index at the time of the deletion.
Example
- Input:
n=10,intervals=[[2, 5], [7, 8]],deletions=[3, 0] - Step 1 (delete index 3): The interval
[2, 5]becomes[2, 4]. The interval[7, 8]shifts to[6, 7]. - Step 2 (delete index 0): The interval
[2, 4]shifts to[1, 3]. The interval[6, 7]shifts to[5, 6]. - Output:
[[1, 3], [5, 6]]
Edge Cases
- Deleting an index that makes an interval length zero (e.g.,
[3, 3]becomes empty). - Multiple deletions in a single interval.
- Deletions occurring before or after all intervals.
Hints
Hint 1
Represent the string as a sequence of indices and keep track of how the mapping from 'original index' to 'current index' changes.
Hint 2
For each deletion, iterate through the intervals: if the index falls inside, reduce the end bound; if it is before the interval, shift both bounds down; if it is after, do nothing.
Hint 3
Consider using a Fenwick tree or a Segment tree if the number of operations requires a complexity better than O(D * I), where D is deletions and I is intervals.
Follow-up questions
- How would you optimize the solution if the number of deletions and intervals were both 10^6?
- If the intervals were overlapping, how would you merge them after each modification?
- What data structure would you use if we needed to support 'range insertion' as well as deletions?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.