973. Stamping The Sequence
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for a sequence of stamp placements to transform a string of '?'s into a target string. The forward process, starting from '??...?' and applying stamps, is complex because later stamps can overwrite parts of earlier ones. This makes it difficult to determine the correct sequence of stamps.
Solution
Stamping The Sequence in Python
class Solution:
def movesToStamp(self, stamp: str, target: str) -> List[int]:
m, n = len(stamp), len(target)
# mismatch_counts[i]: number of characters in window i that don't match the stamp
mismatch_counts = [0] * (n - m + 1)
# mismatch_subscribers[k]: list of windows that cover char k and have a mismatch there
mismatch_subscribers = [[] for _ in range(n)]
queue = collections.deque()
visited_windows = [False] * (n - m + 1)
# Initialization phase
for i in range(n - m + 1):
for j in range(m):
if target[i + j] != stamp[j]:
mismatch_counts[i] += 1
mismatch_subscribers[i + j].append(i)
if mismatch_counts[i] == 0:
queue.append(i)
visited_windows[i] = True
result = []
stamped_chars = [False] * n
stamped_count = 0
# Processing phase
while queue:
i = queue.popleft()
result.append(i)
# For each character in the unstamped window
for j in range(m):
k = i + j
if not stamped_chars[k]:
stamped_chars[k] = True
stamped_count += 1
# This character becoming a wildcard might resolve mismatches for other windows
for p in mismatch_subscribers[k]:
mismatch_counts[p] -= 1
if mismatch_counts[p] == 0 and not visited_windows[p]:
queue.append(p)
visited_windows[p] = True
# Finalization: check if all characters were stamped
if stamped_count != n:
return []
# The result was built in reverse stamping order, so reverse it
return result[::-1]
Stamping The Sequence in Java
class Solution {
public int[] movesToStamp(String stamp, String target) {
int m = stamp.length();
int n = target.length();
char[] sChars = stamp.toCharArray();
char[] tChars = target.toCharArray();
// mismatchCounts[i]: number of characters in window i that don't match the stamp
int[] mismatchCounts = new int[n - m + 1];
// mismatchSubscribers[k]: list of windows that cover char k and have a mismatch there
List<List<Integer>> mismatchSubscribers = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
mismatchSubscribers.add(new ArrayList<>());
}
Queue<Integer> queue = new LinkedList<>();
boolean[] visitedWindows = new boolean[n - m + 1];
// Initialization phase
for (int i = 0; i <= n - m; i++) {
for (int j = 0; j < m; j++) {
if (tChars[i + j] != sChars[j]) {
mismatchCounts[i]++;
mismatchSubscribers.get(i + j).add(i);
}
}
if (mismatchCounts[i] == 0) {
queue.add(i);
visitedWindows[i] = true;
}
}
List<Integer> resultList = new ArrayList<>();
boolean[] stampedChars = new boolean[n];
int stampedCount = 0;
// Processing phase
while (!queue.isEmpty()) {
int i = queue.poll();
resultList.add(i);
// For each character in the unstamped window
for (int j = 0; j < m; j++) {
int k = i + j;
if (!stampedChars[k]) {
stampedChars[k] = true;
stampedCount++;
// This character becoming a wildcard might resolve mismatches for other windows
for (int p : mismatchSubscribers.get(k)) {
mismatchCounts[p]--;
if (mismatchCounts[p] == 0 && !visitedWindows[p]) {
queue.add(p);
visitedWindows[p] = true;
}
}
}
}
}
// Finalization: check if all characters were stamped
if (stampedCount != n) {
return new int[0];
}
// The result was built in reverse stamping order, so reverse it
int[] result = new int[resultList.size()];
for(int i = 0; i < resultList.size(); i++){
result[i] = resultList.get(resultList.size() - 1 - i);
}
return result;
}
}
Stamping The Sequence in C++
class Solution {
public:
vector<int> movesToStamp(string stamp, string target) {
int m = stamp.length();
int n = target.length();
// mismatch_counts[i]: number of characters in window i that don't match the stamp
vector<int> mismatch_counts(n - m + 1, 0);
// mismatch_subscribers[k]: list of windows that cover char k and have a mismatch there
vector<vector<int>> mismatch_subscribers(n);
queue<int> q;
vector<bool> visited_windows(n - m + 1, false);
// Initialization phase
for (int i = 0; i <= n - m; ++i) {
for (int j = 0; j < m; ++j) {
if (target[i + j] != stamp[j]) {
mismatch_counts[i]++;
mismatch_subscribers[i + j].push_back(i);
}
}
if (mismatch_counts[i] == 0) {
q.push(i);
visited_windows[i] = true;
}
}
vector<int> result;
vector<bool> stamped_chars(n, false);
int stamped_count = 0;
// Processing phase
while(!q.empty()) {
int i = q.front();
q.pop();
result.push_back(i);
// For each character in the unstamped window
for (int j = 0; j < m; ++j) {
int k = i + j;
if (!stamped_chars[k]) {
stamped_chars[k] = true;
stamped_count++;
// This character becoming a wildcard might resolve mismatches for other windows
for (int p : mismatch_subscribers[k]) {
mismatch_counts[p]--;
if (mismatch_counts[p] == 0 && !visited_windows[p]) {
q.push(p);
visited_windows[p] = true;
}
}
}
}
}
// Finalization: check if all characters were stamped
if (stamped_count != n) {
return {};
}
// The result was built in reverse stamping order, so reverse it
reverse(result.begin(), result.end());
return result;
}
};
Stamping The Sequence in TypeScript
function movesToStamp(stamp: string, target: string): number[] {
const m = stamp.length;
const n = target.length;
// mismatchCounts[i]: number of characters in window i that don't match the stamp
const mismatchCounts: number[] = new Array(n - m + 1).fill(0);
// mismatchSubscribers[k]: list of windows that cover char k and have a mismatch there
const mismatchSubscribers: number[][] = Array.from({ length: n }, () => []);
const queue: number[] = [];
const visitedWindows: boolean[] = new Array(n - m + 1).fill(false);
// Initialization phase
for (let i = 0; i <= n - m; i++) {
for (let j = 0; j < m; j++) {
if (target[i + j] !== stamp[j]) {
mismatchCounts[i]++;
mismatchSubscribers[i + j].push(i);
}
}
if (mismatchCounts[i] === 0) {
queue.push(i);
visitedWindows[i] = true;
}
}
const result: number[] = [];
const stampedChars: boolean[] = new Array(n).fill(false);
let stampedCount = 0;
// Processing phase
let head = 0;
while (head < queue.length) {
const i = queue[head++];
result.push(i);
// For each character in the unstamped window
for (let j = 0; j < m; j++) {
const k = i + j;
if (!stampedChars[k]) {
stampedChars[k] = true;
stampedCount++;
// This character becoming a wildcard might resolve mismatches for other windows
for (const p of mismatchSubscribers[k]) {
mismatchCounts[p]--;
if (mismatchCounts[p] === 0 && !visitedWindows[p]) {
queue.push(p);
visitedWindows[p] = true;
}
}
}
}
}
// Finalization: check if all characters were stamped
if (stampedCount !== n) {
return [];
}
// The result was built in reverse stamping order, so reverse it
return result.reverse();
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.