Magicsheet logo

Stamping The Sequence

Hard
49.7%
Updated 6/1/2025

Asked by 1 Company

Stamping The Sequence

What is this problem about?

The Stamping The Sequence coding problem is a string manipulation task where you start with a string of question marks "?" of length NN and a "stamp" string. You can place the stamp over any substring of length equal to the stamp, replacing the characters in that range with the stamp's characters. You can perform at most 10N10N stamp operations. The goal is to reach a specific target string. You need to return the sequence of starting indices of the stamps in the order they were applied.

Why is this asked in interviews?

This problem is asked by Morgan Stanley to test a candidate's ability to work backward. It's much easier to start with the target string and "undo" the stamps than to try and build it from scratch. It tests your knowledge of Greedy interview pattern, String processing, and sometimes Queue or Stack usage for managing the "undo" process.

Algorithmic pattern used

The key is to work Backward. We look for a position in the target string that matches our stamp. Once we find it, we "replace" those characters with a wildcard (like '') to represent that those characters are now "don't care" because they could have been covered by a later stamp. We continue this process, finding positions where the stamp matches the target (treating '' as a match for any character). If we can turn the entire target into '*', we've found the sequence in reverse.

Example explanation (use your own example)

Target: "aabcba", Stamp: "abc".

  1. Look for "abc" in "aabcba". Found at index 1: "a[abc]ba".
  2. Replace with wildcards: "a***ba".
  3. Now look for "abc" in "a*ba". We can match index 0: "[a]*ba" (since * matches b and c).
  4. Replace: "****ba".
  5. Now look for "abc" in "ba". We can match index 3: "[]" (matches b and a is actually wrong, let's say stamp was "cba").
  6. If the entire string becomes wildcards, we reverse the indices we found to get the final answer.

Common mistakes candidates make

  • Working forward: Trying to simulate the process from "?????" which leads to an impossible search space.
  • Infinite loops: Not having a way to stop if no more matches can be made.
  • Inefficient matching: Repeatedly scanning the string without keeping track of which indices have already been processed.
  • Limit ignored: Not ensuring the number of operations is within the 10N10N limit (though the backward greedy approach usually stays well within it).

Interview preparation tip

"Reverse Thinking" is a powerful technique. When a process involves overwriting or covering, always ask: "What does the last step look like?" The last stamp applied must be perfectly visible in the final target. This observation is the key to solving this Stamping The Sequence interview question.

Similar Questions