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

  Рет қаралды 13,077

Greg Hogg

Greg Hogg

Күн бұрын

Пікірлер: 46
@GregHogg
@GregHogg 4 ай бұрын
Master Data Structures & Algorithms For FREE at AlgoMap.io!
@omarshahwan4957
@omarshahwan4957 3 ай бұрын
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)
@artemqqq7153
@artemqqq7153 3 ай бұрын
Hi Greg! How can we solve the problem where you given two sorted lists without repeating elements and intersection must be found with complexity of O(n) without using set()?
@artemqqq7153
@artemqqq7153 3 ай бұрын
Hi Greg! How can we solve the problem where you given two sorted lists without repeating elements and intersection must be found with complexity of O(n) without using set()?
@gouravkundu8484
@gouravkundu8484 4 ай бұрын
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
@JoeTan-nq4fq
@JoeTan-nq4fq 2 ай бұрын
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)
@adityaasabe7292
@adityaasabe7292 3 ай бұрын
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
@darrenegbuka9019
@darrenegbuka9019 2 ай бұрын
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 len(word2): ans += word1[shorter:] elif len(word2) > len(word1): ans += word2[shorter:] return ans
@chineduekeneokpala3407
@chineduekeneokpala3407 2 ай бұрын
string contactination is every expensive if you are looking for a more shorter way, use zip()
@ChasingDream2002
@ChasingDream2002 3 ай бұрын
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:])
@SilverSuperGamer
@SilverSuperGamer 4 ай бұрын
Cool video pretty straightforward
@ericrodriguesdeoliveira594
@ericrodriguesdeoliveira594 2 ай бұрын
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
@laxusgaming108
@laxusgaming108 2 ай бұрын
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
@sarthaksaini8440
@sarthaksaini8440 Ай бұрын
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
@gopinathvaradarajan2161
@gopinathvaradarajan2161 Ай бұрын
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)
@anamaysingh1429
@anamaysingh1429 14 күн бұрын
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)
@BlueSoda-c5j
@BlueSoda-c5j 27 күн бұрын
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)
@SooryaaV.R
@SooryaaV.R 3 ай бұрын
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("") };
@MatthewWells-u9u
@MatthewWells-u9u 2 ай бұрын
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
@benatakaan613
@benatakaan613 Ай бұрын
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: combined_words.extend(word1[desired_length:]) else: combined_words.extend(word2[desired_length:]) return ''.join(combined_words)
@MaharsheeKShah
@MaharsheeKShah 4 ай бұрын
Thanks
@2face324
@2face324 4 ай бұрын
# 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))
@ItsHowdy
@ItsHowdy 3 ай бұрын
i thought the same thing. too complicated
@kumaranb8702
@kumaranb8702 4 ай бұрын
Very nice 👍🙂
@kumaranb8702
@kumaranb8702 4 ай бұрын
Great 👍
@edprins1760
@edprins1760 4 ай бұрын
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)])
@edprins1760
@edprins1760 4 ай бұрын
From itertools import zip_longest result = ''.join([(c if c else '')+(d if d else '') for (c,d) in zip_longest(word1,word2)])
@edprins1760
@edprins1760 4 ай бұрын
For memmory efficiëncy: from itertools import zip_longest: result =‘’ for (c,d) in zip_longest(word1,word2): result+=(c if c else '')+ (d if d else '')
@VidhanReddyA
@VidhanReddyA 3 ай бұрын
Well this is better int wordOneLength = word1.length(), wordTwoLength = word2.length(), a = 0, b = 0; string result = ""; while (a < wordOneLength || b < wordTwoLength) { if (a < wordOneLength) { result += word1[a++]; } if (b < wordTwoLength) { result += word2[b++]; } } return result; in C++
@AshutoshKumar-jv1pt
@AshutoshKumar-jv1pt 3 ай бұрын
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)
@omarshahwan4957
@omarshahwan4957 3 ай бұрын
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)
@rodrigoebner2215
@rodrigoebner2215 2 ай бұрын
It can make it faster depending on size of strings, but looking for time complexity, it's also O(n) and that's what interviewers look at usually
@sarathikumark
@sarathikumark 4 ай бұрын
Cool bro
@shehanprasanna3905
@shehanprasanna3905 3 ай бұрын
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
@aidanthompson5053
@aidanthompson5053 3 ай бұрын
2:52
@nirmalgurjar8181
@nirmalgurjar8181 4 ай бұрын
Easy ..
@abdallahtoba7568
@abdallahtoba7568 2 ай бұрын
my solution is faster O(min(n,m)) : python def mergeAlternately(self, word1: str, word2: str) -> str: sol = '' min_len = min(len(word1),len(word2)) for i in range(min_len): sol += word1[i] sol += word2[i] return sol + max(word1,word2,key=len)[min_len:]
@Ak-ggs
@Ak-ggs 2 ай бұрын
the following code is mostly same but a lil bit faster class Solution(object): def mergeAlternately(self, word1, word2): A , B = len(word1), len(word2) a , b = 0, 0 word=1 s='' while a
@attenonmj3708
@attenonmj3708 3 ай бұрын
This is my code, I know I could extract some of it in a new function, but I think I prefer my solution and I would never think to use 2 indexes. Can someone tell me if my solution is bad and why. I also used string1 and string2 instead of word1 and word2, don't ask why. length1 = len(string1) length2 = len(string2) solution = "" if length1 < length2: for i in range(length1): solution += string1[i] + string2[i] solution += string2[length1:] elif length1 > length2: for i in range(length2): solution += string1[i] + string2[i] solution += string1[length2:] else: for i in range(length1): solution += string1[i] + string2[i] return solution
@ItsHowdy
@ItsHowdy 3 ай бұрын
i would like to know too! overall i think it would be too high of runtime having all those forloops.
@shreyageek
@shreyageek 3 ай бұрын
this can be more easier var mergeAlternately = function(word1, word2) { let res ="",i=0,j=0; let len1 = word1.length; let len2 = word2.length; let maxLength = Math.max(len1,len2) while(i < maxLength || j < maxLength){ res += word1[i] ? word1[i] : ""; res += word2[j] ? word2[j] : ""; i++;j++ } return res; };
@shreyageek
@shreyageek 3 ай бұрын
Or probably this var mergeAlternately = function(word1, word2) { let res = ""; let len1 = word1.length; let len2 = word2.length; let i = 0; while (i < len1 || i < len2) { if (i < len1) res += word1[i]; if (i < len2) res += word2[i]; i++; } return res; };
@the8thdeadlysin266
@the8thdeadlysin266 4 ай бұрын
@Greg Why not? a=input() b=input() al=len(a) bl=len(b) new='' i=0 j=0 while al>i and bl>j: new+=a[i] new+=b[j] i+=1 j+=1 while al>i: new+=a[i] i+=1 while bl>j: new+=b[j] j+=1 print(new)
@the8thdeadlysin266
@the8thdeadlysin266 4 ай бұрын
I meant the approach* (not using a string)
@slapfighting
@slapfighting 2 ай бұрын
word1='abc' word2='pqrst' final=[] for i in range(min(len(word1),len(word2))): final.append(word1[i]) final.append(word2[i]) if len(word1)>len(word2): final.append(word1[-(len(word1)-len(word2)):]) elif len(word1)
Top K Frequent Elements - Leetcode 347 - Heaps (Python)
14:08
Greg Hogg
Рет қаралды 11 М.
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 687 М.
Players vs Pitch 🤯
00:26
LE FOOT EN VIDÉO
Рет қаралды 133 МЛН
Noodles Eating Challenge, So Magical! So Much Fun#Funnyfamily #Partygames #Funny
00:33
5 Useful F-String Tricks In Python
10:02
Indently
Рет қаралды 329 М.
I Studied Data Job Trends for 24 Hours to Save Your Career! (ft Datalore)
13:07
Thu Vu data analytics
Рет қаралды 278 М.
Coin Change - Leetcode 322 - Dynamic Programming (Python)
15:27
All Rust string types explained
22:13
Let's Get Rusty
Рет қаралды 183 М.
Number of Islands - Leetcode 200 - Graphs (Python)
11:01
Greg Hogg
Рет қаралды 10 М.
Roman to Integer - Leetcode 13 - Arrays & Strings (Python)
6:15
String Compression - LeetCode 443 - Python #leetcode75 #leetcode
12:04