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 INPUT stamp = "abc" a b c target = "ababc" a b a b c 0 1 2 3 4 Initial s: ? ? ? ? ? Goal: Convert s to target Max turns: 50 ALGORITHM STEPS Greedy Reverse Stamping 1 Work Backwards Start from target, find stamp matches to "unstamp" 2 Find "abc" at idx 2 target[2:5] = "abc" Replace with "???" ab abc ab ??? 3 Find "ab?" at idx 0 Partial match counts! Replace with "???" ab ??? ????? 4 All '?' = Success Record indices in reverse order: [0, 2] FINAL RESULT Forward Stamping Order: Turn 1: Stamp at index 0 a b c ? ? abc?? Turn 2: Stamp at index 2 a b a b c ababc Output: [0, 2] OK - Target achieved! 2 turns used (max: 50) Key Insight: Work backwards from target! Instead of figuring out where to stamp, find where stamp matches in target and "unstamp" by replacing with '?'. Partial matches (with existing '?') are valid. Reverse the order of found indices for the final answer. Greedy approach works! TutorialsPoint - Stamping The Sequence | Greedy Reverse Stamping Approach
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