
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find largest merge of two strings in Python
Suppose we have two strings s and t. We want to form 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.
Finally, we have to find the lexicographically largest merge that we can form.
So, if the input is like s = "zxyxx" t = "yzxxx", then the output will be "zyzxyxxxxx"
To solve this, we will follow these steps −
a := 0, b := 0
merge := blank string
W1 := size of s
W2 := size of t
while a < W1 and b < W2, do
if substring of s from index a to end > substring of t from index b to end, then
merge := merge concatenate s[a]
a := a + 1
otherwise,
merge := merge concatenate t[b]
b := b + 1
return merge concatenate (substring of s from index a to end) concatenate (substring of t from index b to end)
Example
Let us see the following implementation to get better understanding −
def solve(s, t): a = b = 0 merge = "" W1 = len(s) W2 = len(t) while a < W1 and b < W2: if s[a:] > t[b:]: merge += s[a] a += 1 else: merge += t[b] b += 1 return merge + s[a:] + t[b:] s = "zxyxx" t = "yzxxx" print(solve(s, t))
Input
"zxyxx", "yzxxx"
Output
zyzxyxxxxx
- Related Articles
- Largest Merge of Two Strings in Python
- Largest Merge of Two Strings in C++
- Program to merge two strings in alternating fashion in Python
- Program to get maximum length merge of two given strings in Python
- Program to merge strings alternately using Python
- Python program to merge two Dictionaries
- Python Program to Merge two Tuples
- Program to find the largest product of two distinct elements in Python
- How to merge two strings alternatively in JavaScript
- Program to find largest substring between two equal characters in Python
- Python program to find uncommon words from two Strings
- Program to find largest distance pair from two list of numbers in Python
- Program to find size of common special substrings of two given strings in Python
- Python - Ways to merge strings into list
- Python Program to Merge Two Lists and Sort it
