Shortest Way to Form String — LeetCode 1055 Python Solution
- Problem
- #1055
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n), where m and n are the lengths of the strings `source` and `target` respectively |
| Space | O(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.