Merge Strings Alternately

Problem Id: 1768 Difficulty: Easy Tag: String



We are given 2 words, word1 and word2. Each word contains at most 100 characters.


We are asked to merge this 2 words. The limitation of the merge is that each characters should be picked from 2 words one by one.

About Code

The solution is simple. We have 2 indices i and j. i is the current candidate character in word1, and j is the current candidate character in word2. The only one thing we need to pay attention to is the index should be smaller than the length of the word, i < len(word1) and j < len(word2).


class Solution:
    def mergeAlternately(self, word1, word2):
        merged = []
        i = j = 0
        while i < len(word1) or j < len(word2):
            if i < len(word1):
                i += 1
            if j < len(word2):
                j += 1
        return ''.join(merged)