Make String a Subsequence Using Cyclic Increments — LeetCode 2825 Python Solution

MediumTwo PointersString
Problem
#2825
Reading time
2 min

The 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.

Example

Input
str1 = "abc", str2 = "ad"
Output
true
Explanation
Select index 2 in str1.

Python solution

Python
class Solution:
    def canMakeSubsequence(self, str1: str, str2: str) -> bool:
        i = 0
        for c in str1:
            d = "a" if c == "z" else chr(ord(c) + 1)
            if i < len(str2) and str2[i] in (c, d):
                i += 1
        return i == len(str2)

Complexity

MeasureComplexity
TimeO(m + n), where m and n are the lengths of the strings str1 and str2 respectively
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2825. Make String a Subsequence Using Cyclic Increments is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2825. Make String a Subsequence Using Cyclic Increments?
LeetCode 2825. Make String a Subsequence Using Cyclic Increments is rated Medium on LeetCode.
What is the time complexity of LeetCode 2825. Make String a Subsequence Using Cyclic Increments?
The Python solution on this page runs in O(m + n), where m and n are the lengths of the strings str1 and str2 respectively.
What is the space complexity of LeetCode 2825. Make String a Subsequence Using Cyclic Increments?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2825. Make String a Subsequence Using Cyclic Increments cover?
LeetCode 2825. Make String a Subsequence Using Cyclic Increments is tagged Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview