Shortest Way to Form String — LeetCode 1055 Python Solution

MediumLeetCode PremiumGreedyTwo PointersStringBinary Search
Problem
#1055
Reading time
3 min

The problem

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

Example

Input
source = "abc", target = "abcbc"
Output
2
Explanation
The target "abcbc" can be formed by "abc" and "bc", which are subsequences of source "abc".

Python solution

Python
class Solution:
    def shortestWay(self, source: str, target: str) -> int:
        def f(i, j):
            while i < m and j < n:
                if source[i] == target[j]:
                    j += 1
                i += 1
            return j

        m, n = len(source), len(target)
        ans = j = 0
        while j < n:
            k = f(0, j)
            if k == j:
                return -1
            j = k
            ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(m \times n), where m and n are the lengths of the strings `source` and `target` respectively
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1055. Shortest Way to Form String is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

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 1055. Shortest Way to Form String?
LeetCode 1055. Shortest Way to Form String is rated Medium on LeetCode.
What is the time complexity of LeetCode 1055. Shortest Way to Form String?
The Python solution on this page runs in O(m \times n), where m and n are the lengths of the strings `source` and `target` respectively.
What is the space complexity of LeetCode 1055. Shortest Way to Form String?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1055. Shortest Way to Form String cover?
LeetCode 1055. Shortest Way to Form String is tagged Greedy, Two Pointers, String and Binary Search on LeetCode.
Is LeetCode 1055. Shortest Way to Form String a premium problem?
Yes. LeetCode 1055. Shortest Way to Form String is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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