Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Finds the minimum number of subsequences of 'source' required to form 'target'.
- Returns -1 if 'target' cannot be formed from 'source'.
- """
- def solve(source: str, target: str) -> int:
- """
- Time Complexity: O(len(source) * len(target))
- Space Complexity: O(1)
- """
- answer = 0
- # Greedy, match as many as you can
- def match_subsequence(source_idx: int, target_idx: int) -> int:
- while source_idx < len(source) and target_idx < len(target):
- if source[source_idx] == target[target_idx]:
- target_idx += 1
- source_idx += 1 # subsequence -> able to skip it
- return target_idx
- target_idx = 0
- while target_idx < len(target):
- new_target_idx = match_subsequence(0, target_idx)
- if new_target_idx == target_idx:
- answer = -1
- break
- else:
- target_idx = new_target_idx
- answer += 1
- return answer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement