- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to get maximum length merge of two given strings in Python
Suppose we have two strings s and t. We have to make a string called merge in the following way: while either s or t are non-empty, select one of the following options −
If s is non-empty, then append the first character in s to merge and delete it from s.
If t is non-empty, then append the first character in t to merge and delete it from t.
So we have to find the lexicographically largest merge we can make.
So, if the input is like s = "zxyxx" t = "yzxxx", then the output will be zyzxyxxxxx, because
Pick from s: merge = "z", s = "xyxx", t = "yzxxx"
Pick from t: merge = "zy", s = "xyxx", t = "zxxx"
Pick from t: merge = "zyz", s = "xyxx", t = "xxx"
Pick from s: merge = "zyzx", s = "yxx", t = "xxx"
Pick from s: merge = "zyzxy", s = "xx", t = "xxx"
Then add the remaining 5 x's from s and t at the end of merge.
To solve this, we will follow these steps −
ans := blank string
idx1 := 0, idx2 := 0
while idx1 < size of s and idx2 < size of t, do
if s[idx1] > t[idx2] or (s[idx1] is same as t[idx2] and substring of s[from index idx1 to end] >= substring of t[from index idx2 to end]), then
ans := ans concatenate s[idx1]
idx1 := idx1 + 1
otherwise when s[idx1] < t[idx2] or (s[idx1] is same as t[idx2] and substring of s[from index idx1 to end] <= substring of t[from index idx2 to end]), then
ans := ans concatenate t[idx2]
idx2 := idx2 + 1
return ans concatenate s[from index idx1 to end] concatenate t[from index idx2 to end]
Let us see the following implementation to get better understanding −
def solve(s, t): ans = "" idx1 = idx2 = 0 while(idx1<len(s) and idx2<len(t)): if s[idx1]>t[idx2] or (s[idx1]==t[idx2] and s[idx1:]>=t[idx2:]): ans+=s[idx1] idx1+=1 elif s[idx1]<t[idx2] or (s[idx1]==t[idx2] and s[idx1:]<=t[idx2:]): ans+=t[idx2] idx2+=1 return ans+s[idx1:]+t[idx2:] s = "zxyxx" t = "yzxxx" print(solve(s, t))
- Program to find largest merge of two strings in Python
- Largest Merge of Two Strings in Python
- Program to merge two strings in alternating fashion in Python
- Largest Merge of Two Strings in C++
- Program to merge strings alternately using Python
- Program to equal two strings of same length by swapping characters in Python
- Python program to merge two Dictionaries
- Python Program to get K length groups with given summation
- Python - Merge DataFrames of different length
- Program to find size of common special substrings of two given strings in Python
- Program to find maximum length of k ribbons of same length in Python
- Maximum Nesting Depth of Two Valid Parentheses Strings in Python
- C++ program to get length of strings, perform concatenation and swap characters