Skip to content

Instantly share code, notes, and snippets.

@hongtaoh
Created October 25, 2024 16:53
Show Gist options
  • Save hongtaoh/791547ee832241a01c0bf92725f73c39 to your computer and use it in GitHub Desktop.
Save hongtaoh/791547ee832241a01c0bf92725f73c39 to your computer and use it in GitHub Desktop.
Solution to Leetcode 1768
class Solution:
"""
This is okay but unnecessarily complicated.
if a = [1, 2, 3], then a[4:] won't cause any errors. This will help me get a better solution.
"""
def mergeAlternately(self, word1: str, word2: str) -> str:
# len1 < len2
len1, len2 = (len(word1), len(word2)) if len(word1) < len(word2) else (len(word2), len(word1))
output = []
for i in range(len1):
output.append(word1[i])
output.append(word2[i])
if len1 == len(word1):
output.append(word2[len1:])
elif len1 != len2:
output.append(word1[len1:])
return "".join(output)
@hongtaoh
Copy link
Author

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        i, j = 0, 0
        res = []
        while i < len(word1) and j < len(word2):
            res.append(word1[i])
            res.append(word2[j])
            i += 1
            j += 1
        res.append(word1[i:])
        res.append(word2[j:])

        return "".join(res)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment