Merge Strings Alternately - Leetcode 1768 - Arrays & Strings (Python)

preview_player
Показать описание


Please check my playlists for free DSA problem solutions:

My Favorite Courses:

Data Structures & Algorithms:

Python:

Web Dev / Full Stack:

Cloud Development:

Game Development:

SQL & Data Science:

Machine Learning & AI:
Рекомендации по теме
Комментарии
Автор

Master Data Structures & Algorithms For FREE at AlgoMap.io!

GregHogg
Автор

class Solution(object):
def mergeAlternately(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: str
"""

k=0
ans=''
for index, i in enumerate(word1):
if k==index-1 and k<len(word2):
ans+=word2[k]
k+=1
ans+=word1[index]
if k<len(word2):
ans+=word2[k:]

return ans
this code has a time complexity of o(n) n=length of word 1

gouravkundu
Автор

you can skip the first 0 index because word1 and word2 min length is 1

A, B = len(word1), len(word2)
a = b = 1
s = [word1[0], word2[0]]
while a < A and b < B:
s.append(word1[a])
a+=1
s.append(word2[b])
b+=1
while a < A:
s.append(word1[a])
a+=1
while b < B:
s.append(word2[b])
b+=1
return "".join(s)


you could do slices too after the first while
if A > B:
s.append(word1[a:])
else:
s.append(word2[b:])

ChasingDream
Автор

length = min(len(word1), len(word2))

s = []
for i in range(length):
s.append(word1[i])
s.append(word2[i])

s.append(word1[length:])
s.append(word2[length:])

return ''.join(s)

i think this is much easier

adityaasabe
Автор

Since we are using list s to store the result, we can use s.extend([word1[a], word2[b]). Hence, there's no need to keep track of word = 1 or 2. For appending the remaining characters in the longer string, use s.append(word1[a:]) or s.append(word2[b:]. In fact, we can do away with pointer b since a is always equal to b
####
word = []
a = 0 # Define pointer for word1 and word2

# Combine the chars
while a < (n := len(word1)) and a < (m := len(word2)):
word.extend([word1[a], word2[a]])
a += 1

# Append remaining chars
word.append(word1[a:]) if n > m else word.append(word2[a:])

return ''.join(word)

JoeTan-nqfq
Автор

Good solution. I found a shorter way. this is my code that got accepted:

class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
shorter = min(len(word1), len(word2))
ans = ""
index = 0
while index <= shorter - 1:
ans += word1[index]
ans += word2[index]
index += 1
if len(word1) > len(word2):
ans += word1[shorter:]
elif len(word2) > len(word1):
ans += word2[shorter:]
return ans

darrenegbuka
Автор

class Solution(object):
def mergeAlternately(self, word1, word2):

joined = word1+word2
size = len(joined)
ans=""
print(size)
i = 0
while i < size:
if i < len(word1):
ans+=word1[i]
if i < len(word2):
ans+=word2[i]
i = i + 1

return ans

ericrodriguesdeoliveira
Автор

class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
strr = ""
for i in range(min(len(word1), len(word2))):
strr += word1[i] + word2[i]

if len(word1) < len(word2):
strr += word2[len(word1):]

if len(word1) > len(word2):
strr += word1[len(word2):]

return strr

sarthaksaini
Автор

class Solution(object):
def mergeAlternately(self, word1, word2):
merged = []

for i in range(max(len(word1), len(word2))):
if i < len(word1):
merged.append(word1[i])
if i < len(word2):
merged.append(word2[i])


return ''.join(merged)

gopinathvaradarajan
Автор

class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
pointer1 = word1.lower()
pointer2 = word2.lower()
pointer3 = ""
for i in range(max(len(pointer1), len(pointer2))):
if i < len(pointer1):
pointer3 += pointer1[i]
if i < len(pointer2):
pointer3 += pointer2[i]

return pointer3

laxusgaming
Автор

class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
len1, len2 = len(word1), len(word2)
length = min(len1, len2)
l = []

for i in range(length):
l.append(word1[i]) if i < len1 else None
l.append(word2[i]) if i < len2 else None

return "".join(l)

BlueSoda-cj
Автор

JS code, used single while

var mergeAlternately = function(word1, word2) {
let word = [];
let a = 0, b = 0;

while (a < word1.length && b < word2.length){
word.push(word1[a]);
word.push(word2[b]);
a+=1;
b+=1;
}

if (word1.length > word2.length){
word.push(word1.slice(a, word1.length));
}else{
word.push(word2.slice(b, word2.length));
}

return word.join("")


};

SooryaaV.R
Автор

I guess this is a more optimised code?:

def mergeAlternately(self, word1: str, word2: str) -> str:
n1, n2 = len(word1), len(word2)
n = max(n1, n2)
res = []
for i in range(n):
if i < n1:
res.append(word1[i])
if i < n2:
res.append(word2[i])
return "".join(res)

anamaysingh
Автор

class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
desired_length = min(len(word1), len(word2))
combined_words = [word1[i] + word2[i] for i in range(desired_length)]
if len(word1) > desired_length:

else:

return ''.join(combined_words)

benatakaan
Автор

class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
new_string = ""
limit = len(word1)
if len(word2) < limit:
limit = len(word2)

for i in range(limit):
new_string += word1[i]
new_string += word2[i]

if limit == len(word1):
new_string += word2[limit:]
else:
new_string += word1[limit:]

return new_string

MatthewWells-uu
Автор

# Here's my solution. Your first while loop is too complicated, at least for me :-)

word1 = "abc"
word2 = "defgh"

A, B = len(word1), len(word2)
a = b = min(A, B)
s = []

i = 0
while i < a:
s.append(word1[i])
s.append(word2[i])
i += 1

while a < A:
s.append(word1[a])
a += 1

while b < B:
s.append(word2[b])
b += 1

print(''.join(s))

face
Автор

Oneliner with w1 and w2 as word1 and word2. c and d as character in tuple from the common section of a and b.

''.join([c+d for (c, d) in zip(w1, w2)])+(w1[len(w2):len(w1)])+(w2[len(w1):len(w2)])

edprins
Автор

Is this any faster or does the first if statement make it slower?

ans = []
if len(word1) > len(word2):
longest = word1
else:
longest = word2
for i in range(len(longest)):
if i < len(word1):
ans.append(word1[i])
if i < len(word2):
ans.append(word2[i])

return ''.join(ans)

omarshahwan
Автор

My solution for this problem which is much simpler:
class Solution:

def mergeAlternately(self, word1: str, word2: str) -> str:
s_list = min(len(word1), len(word2))
merged_str = ""

for i in range(s_list):
merged_str += word1[i] + word2[i]

merged_str += word1[s_list::]
merged_str += word2[s_list::]

return merged_str

Time complexity of O(n)

AshutoshKumar-jvpt
Автор

def mergeAlternately(self, word1, word2):
new_word = ""
len1, len2 = len(word1), len(word2)
length = min(len1, len2)

for i in range(length):
new_word += word1[i] + word2[i]

new_word += word1[length:] + word2[length:]
return new_word

shehanprasanna