Stamping The Sequence - Problem

You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'.

In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp. For example, if stamp = "abc" and target = "abcba", then s is "?????" initially. In one turn you can:

  • place stamp at index 0 of s to obtain "abc??"
  • place stamp at index 1 of s to obtain "?abc?"
  • place stamp at index 2 of s to obtain "??abc"

Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s).

We want to convert s to target using at most 10 * target.length turns. Return an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns, return an empty array.

Input & Output

Example 1 — Basic Case
$ Input: stamp = "abc", target = "ababc"
Output: [0,2]
💡 Note: Start with "?????". Stamp at position 0: "abc??". Stamp at position 2: "ababc" matches target.
Example 2 — Single Stamp
$ Input: stamp = "abc", target = "abc"
Output: [0]
💡 Note: Target matches stamp exactly, so one stamp at position 0 creates the target.
Example 3 — Impossible Case
$ Input: stamp = "abc", target = "aabcb"
Output: []
💡 Note: Cannot create target with given stamp - the 'aa' at start cannot be formed by 'abc'

Constraints

  • 1 ≤ stamp.length ≤ target.length ≤ 1000
  • stamp and target consist of lowercase English letters

Visualization

Tap to expand
Stamping The Sequence: Transform ????? to abcbaInitial: ????? (stamp = "abc")Stamp at pos 0: abc??Stamp at pos 2: abcbaTarget: abcba achieved!Return: [0, 2] (positions where stamp was placed)
Understanding the Visualization
1
Initial State
String s filled with '?' characters
2
Stamping Process
Place stamp at various positions to build target
3
Target Achieved
Return sequence of positions used
Key Takeaway
🎯 Key Insight: Work backwards from target by greedily removing stamp patterns to avoid exponential search
Asked in
Google 15 Facebook 8
12.0K Views
Medium Frequency
~35 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen