1614. Pattern Purge Chain

Hard7.5 points estimatedLinked ListString MatchingStack

A conveyor carries coloured tags stored as the singly linked list head, and a sorting rule is given by the integer array pattern. Repeatedly find the leftmost place where the values of pattern appear as consecutive nodes and delete those nodes, letting their neighbours join up, until no occurrence is left. Return the head of what remains, or null if nothing remains. Deleting a block can create a new occurrence across the seam, so a single pass is not enough by itself. The list has up to 100000 nodes, the pattern has 1 to 100000 values, and all values lie in [0, 10^9]. Scan once with a stack that stores each kept node's KMP matched length; when it reaches the pattern length, pop that many entries and resume from the state below: O(n + m) time and space.

Example 1

Input:
head = [1,2,3,2,3,4], pattern = [2,3]
Output:
[1,4]
Explanation:

Deleting the first 2, 3 leaves 1, 2, 3, 4 and then the next 2, 3 goes too, leaving 1, 4.

Example 2

Input:
head = [5,5,5], pattern = [5,5]
Output:
[5]
Explanation:

The leftmost pair is removed and a single 5 remains.

Example 3

Input:
head = [1,2,3], pattern = [4]
Output:
[1,2,3]
Explanation:

The pattern never occurs, so the list is unchanged.

Constraints

0 ≤ length ≤ 105

1 ≤ pattern.length ≤ 105

0 ≤ val, pattern[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n + m)
Space
O(n + m)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…