Leetcode 75 #1
Leetcode 75 #1
1768. Merge Strings Alternately
I have decided to start up a daily/weekly coding challenge for myself on the Leetcode platform to revamp some of my algorithms knowledge I may have forgotten over the years.
Here is the first of the Leetcode 75!
Algorithm | Runtime | Memory |
---|---|---|
A | 32ms | 16.6mb |
B | 25ms | 16.5mb |
Algorithm A: Two pointers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
merged_string = ""
left = right = 0
while left < len(word1) or right < len(word2):
if left < len(word1):
merged_string += word1[left]
left += 1
if right < len(word2):
merged_string += word2[right]
right += 1
return merged_string
Algorithm B: One Pointer
I rewrote it to just play around and see if converting the original word1 parameter into a list would be any faster. I think it has to do with how python can sometimes utilize the same underlying data structure, and remaps a subset of the old object to create the new object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
word1 = list(word1)
left = 0
while left < len(word1):
if left >= len(word2):
break
word1.insert(2 * left + 1, word2[left])
left += 1
word1 += word2[left:]
return "".join(word1)
Over multiple tests, on average, one pointer was significantly faster (21.00+ %)
This post is licensed under CC BY 4.0 by the author.