Make String a Subsequence Using Cyclic Increments - Problem

You are given two 0-indexed strings str1 and str2.

In an operation, you select a set of indices in str1, and for each index i in the set, increment str1[i] to the next character cyclically. That is 'a' becomes 'b', 'b' becomes 'c', and so on, and 'z' becomes 'a'.

Return true if it is possible to make str2 a subsequence of str1 by performing the operation at most once, and false otherwise.

Note: A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.

Input & Output

Example 1 — Basic Match
$ Input: str1 = "abc", str2 = "acd"
Output: true
💡 Note: We can increment str1[2] from 'c' to 'd', making str1 = "abd". Then "acd" is a subsequence: 'a' matches str1[0], 'c' is skipped, 'd' matches str1[2].
Example 2 — No Match Possible
$ Input: str1 = "zc", str2 = "ad"
Output: false
💡 Note: Even with increments: 'z'→'a' and 'c'→'d' gives "ad", but we need "ad" as subsequence. Since both characters are used, we can't form the subsequence.
Example 3 — Cyclic Wrap Around
$ Input: str1 = "za", str2 = "aa"
Output: true
💡 Note: We can increment str1[0] from 'z' to 'a' (cyclic), making str1 = "aa". Then "aa" is a subsequence of "aa".

Constraints

  • 1 ≤ str1.length, str2.length ≤ 105
  • str1 and str2 consist of only lowercase English letters

Visualization

Tap to expand
Make String a Subsequence Using Cyclic IncrementsOriginal str1:abcTarget str2:acdIncrement c → dModified str1:abd"acd" is subsequence of "abd" ✓
Understanding the Visualization
1
Input Strings
str1 = "abc", str2 = "acd"
2
Apply Increments
Increment 'c' to 'd' cyclically (c + 1 = d)
3
Check Subsequence
"acd" is subsequence of modified "abd"
Key Takeaway
🎯 Key Insight: Use greedy two-pointer matching - each character can stay same or increment by one
Asked in
Google 15 Meta 12 Amazon 10
28.5K Views
Medium Frequency
~18 min Avg. Time
845 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