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[1] from 'b' to 'c' and str1[2] from 'c' to 'd', making str1 = "acd". Then "acd" is a subsequence of "acd".
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 Increments INPUT str1 = "abc" a i=0 b i=1 c i=2 str2 = "acd" a j=0 c j=1 d j=2 Cyclic Increment: a-->b, b-->c, c-->d ... z-->a Goal: Make str2 a subsequence of str1 ALGORITHM STEPS 1 Two Pointers i for str1, j for str2 2 Match Check str1[i]==str2[j] OR str1[i]+1==str2[j] 3 Advance Pointers Match: i++, j++ No match: i++ only 4 Return Result j == len(str2)? Matching Process: i=0,j=0: a==a [OK] j++ i=1,j=1: b+1=c [OK] j++ i=2,j=2: c+1=d [OK] j++ j=3 == len(str2) TRUE FINAL RESULT true str2 is a subsequence of modified str1 Transformation: "abc" increment b,c "acd" contains "acd" Key Insight: Use two-pointer technique: for each char in str1, check if it matches str2[j] directly OR after cyclic increment. Time: O(n), Space: O(1). Match means char equals or char+1 equals target (with z-->a wrap). If j reaches end of str2, all chars matched as subsequence. Single pass greedy approach is optimal. TutorialsPoint - Make String a Subsequence Using Cyclic Increments | Optimal Solution
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