#2825

Make String a Subsequence Using Cyclic Increments

Medium
Two PointersStringTwo PointersString Matching
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a two-pointer technique to efficiently check if str2 can be formed as a subsequence of str1 after at most one increment operation. This reduces unnecessary checks and improves performance.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two pointers, one for str1 and one for str2.
  2. 2Step 2: Iterate through both strings, comparing characters at the current pointers.
  3. 3Step 3: If characters match, move both pointers forward. If they don't, check if str1's character can be incremented to match str2's character.
  4. 4Step 4: If all characters in str2 are matched by the end of the iteration, return true. Otherwise, return false.
solution.py11 lines
1# Full working Python code
2
3def canMakeSubsequence(str1, str2):
4    i, j = 0, 0
5    while i < len(str1) and j < len(str2):
6        if str1[i] == str2[j]:
7            j += 1
8        elif (ord(str1[i]) + 1 - ord('a')) % 26 == (ord(str2[j]) - ord('a')):
9            j += 1
10        i += 1
11    return j == len(str2)

Complexity note: This complexity is achieved because we only traverse each string once, making it linear in relation to the length of str1.

  • 1Understanding cyclic increments is crucial to solving this problem.
  • 2Two pointers can efficiently manage the matching process between the two strings.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.