Find the Sequence of Strings Appeared on the Screen - Problem

You are given a string target. Alice is going to type target on her computer using a special keyboard that has only two keys:

  • Key 1 appends the character "a" to the string on the screen.
  • Key 2 changes the last character of the string on the screen to its next character in the English alphabet. For example, "c" changes to "d" and "z" changes to "a".

Note that initially there is an empty string "" on the screen, so she can only press Key 1 first.

Return a list of all strings that appear on the screen as Alice types target, in the order they appear, using the minimum key presses.

Input & Output

Example 1 — Basic Case
$ Input: target = "abc"
Output: ["a","aa","ab","aba","abb","abc"]
💡 Note: Start empty → add 'a' → add 'a' to get 'aa' → cycle to 'ab' → add 'a' to get 'aba' → cycle to 'abb' → cycle to 'abc'
Example 2 — Single Character
$ Input: target = "a"
Output: ["a"]
💡 Note: Only need to add 'a' once, no cycling required
Example 3 — Cycling Required
$ Input: target = "za"
Output: ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","za"]
💡 Note: First position cycles through entire alphabet to reach 'z', then add 'a'

Constraints

  • 1 ≤ target.length ≤ 1000
  • target consists of lowercase English letters only

Visualization

Tap to expand
Find the Sequence of Strings on Screen INPUT Target String: a b c idx 0 idx 1 idx 2 Special Keyboard: Key 1 Append 'a' Key 2 Next char target = "abc" Initial: "" (empty) ALGORITHM STEPS 1 Build char by char Process each target[i] 2 Press Key 1 first Append 'a' to string 3 Press Key 2 N times Cycle: a--b--c--d... 4 Record each state Add to result list Trace for "abc": "" + Key1 --> "a" "a" + Key1 --> "aa" (need 'b', not 'a') "aa" + Key2 --> "ab" "ab" + Key1 --> "aba" "aba"+ Key2 --> "abb" "abb"+ Key2 --> "abc" FINAL RESULT Output Array: "a" "aa" "ab" "aba" "abb" "abc" Wait - actual output: ["a", "aa", "ab", "aba", "abb", "abc"] 6 strings total OK - Minimum Steps! Total key presses: 6 Key Insight: For each character in target, we must first append 'a' (Key 1), then increment to the desired character (Key 2). The minimum presses = sum of (target[i] - 'a' + 1) for each character. Each intermediate string is recorded. TutorialsPoint - Find the Sequence of Strings Appeared on the Screen | Optimal Solution
Asked in
Google 23 Microsoft 15
12.5K Views
Medium Frequency
~15 min Avg. Time
234 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