#936

Stamping The Sequence

Hard
StringStackGreedyQueueGreedyQueueString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages a greedy approach combined with a queue to efficiently track the indices where stamping can occur. By marking characters that have been stamped, we can avoid unnecessary checks and ensure we reach the target string in fewer operations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a queue to track indices where stamping can occur and a boolean array to mark stamped positions.
  2. 2Step 2: For each position in target, check if stamping can occur and enqueue valid indices.
  3. 3Step 3: While the queue is not empty, dequeue an index, stamp it, and mark the corresponding positions.
  4. 4Step 4: Continue until all characters in target are stamped or until the maximum allowed turns are reached.
solution.py27 lines
1from collections import deque
2
3def movesToStamp(stamp, target):
4    s = '?' * len(target)
5    result = []
6    stamped = [False] * len(target)
7    queue = deque()
8    while True:
9        made_change = False
10        for i in range(len(target) - len(stamp) + 1):
11            if can_stamp(s, target, stamp, i) and not stamped[i]:
12                s = stamp_at(s, stamp, i)
13                stamped[i:i + len(stamp)] = [True] * len(stamp)
14                queue.append(i)
15                made_change = True
16        if not made_change:
17            break
18    return list(queue) if s == target else []
19
20def can_stamp(s, target, stamp, index):
21    for j in range(len(stamp)):
22        if s[index + j] != '?' and s[index + j] != stamp[j]:
23            return False
24    return True
25
26def stamp_at(s, stamp, index):
27    return s[:index] + stamp + s[index + len(stamp):]

Complexity note: The optimal solution runs in O(n) time because we efficiently track the positions that can be stamped and avoid redundant checks, leading to a linear pass through the target string.

  • 1Understanding how to track positions for stamping is crucial.
  • 2Greedy algorithms can significantly reduce the number of operations needed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.