
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Minimum Number of Subsequences in Python
Suppose we have two strings source and target, we have to find the minimum number of subsequences of source we can form such that if we concatenate them, it will be same as target. If there is no such result, return -1.
So, if the input is like source = "xyz" target = "xyzyzz", then the output will be 3, as we can concatenate these ["xyz" + "yz" + "z"]
To solve this, we will follow these steps −
- s_size := size of s, t_size := size of t
- concat_count := 0, target_idx := 0
- while target_idx < t_size, do
- source_idx := 0
- temp_index := target_idx
- while source_idx < s_size and target_idx < t_size, do
- if s[source_idx] is same as t[target_idx], then
- target_idx := target_idx + 1
- source_idx := source_idx + 1
- if s[source_idx] is same as t[target_idx], then
- if temp_index is same as target_idx, then
- return -1
- concat_count := concat_count + 1
- return concat_count
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s, t): s_size, t_size = len(s), len(t) concat_count = 0 target_idx = 0 while target_idx < t_size: source_idx = 0 temp_index = target_idx while source_idx < s_size and target_idx < t_size: if s[source_idx] == t[target_idx]: target_idx += 1 source_idx += 1 if temp_index == target_idx: return -1 concat_count += 1 return concat_count ob = Solution() source = "xyz" target = "xyzyzz" print(ob.solve(source, target))
Input
"xyz", "xyzyzz"
Output
3
Advertisements