Key takeaways:
Given two strings
word1
andword2
, merge them by alternating characters starting withword1
. If one string is longer than the other, append the remaining characters to the end.The constraints are
1 <= word1.length, word2.length <= 100
. Both strings consist of lowercase English letters.Use two pointers,
i
forword1
andj
forword2
, both starting at index 0. Append characters alternately from both words to the result string.If one string is exhausted, append the remaining characters of the longer string.The time complexity is
, where m
is the length ofword1
andn
is the length ofword2
.The space complexity is
, as the solution uses only constant extra space for variables and pointers.
In this Answer, we’ll explore the Merge Strings Alternatively problem, which is asked in technical interviews at top tech companies such as Google, Facebook, Amazon, Uber, and Microsoft. We will review a few sample examples, provide short quizzes related to the problem to brainstorm an optimized approach to the problem, and discuss efficient approaches to solve it. By the end of this Answer, you’ll have a solid understanding of how to tackle this problem effectively in your interviews.
Given two strings word1
and word2
, we have to merge the strings by adding letters in alternating order, starting with word1
. If a string is longer than the other, append the additional letters to the end of the merged string. Return the merged string.
Constraints:
word1.length
, word2.length
word1
and word2
consist of lowercase English letters.
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Merge Strings Alternatively
What will be the correct output if we merge the following two strings?
word1
= “merge”
word2
= “strings”
"mergestrings"
"stringsmerge"
"msetrgrngs"
"msetrrgiengs"
To merge strings alternatively, we need to keep track of the characters in both words. To do this, the most feasible approach that should come to mind is to initialize two pointers, both pointing at the first characters of both words.
Let’s say we have a pointer i
, and a pointer j
, both initialized to 0
and a results
string that will be used to return the final output. We start by iterating over both strings until i
or j
reach the end of word1
or word2
respectively. We first check if i
is less than the length of word1
, if this is TRUE
, we append this character from word1
to results
and increment i
. Then we check the same thing for word2
, if j
is less than the length of word2
, we append this character from word2
to results
and increment j
. We keep repeating this process while there are remaining characters in either word1
or word2
. Once all of the characters have been appended to results
, we return.
Let’s look at the following illustration to get a better understanding of the solution:
Let’s look at the code for this solution below:
def merge_strings_alternately(word1, word2):m = len(word1)n = len(word2)i = 0j = 0result = ""# Iterate through both stringswhile i < m or j < n:if i < m:result += word1[i] # Append character from word1i += 1if j < n:result += word2[j] # Append character from word2j += 1return resultdef main():word1_list = ["abc", "astrology", "universe"]word2_list = ["def", "physics", "galaxy"]for i in range(len(word1_list)):print(f"{i + 1}.\t word1 = '{word1_list[i]}'")print(f"\t word2 = '{word2_list[i]}'")result = merge_strings_alternately(word1_list[i], word2_list[i])print(f"\n\t After merging, the final string becomes: '{result}'")print("-" * 100)if __name__ == "__main__":main()
Now, let’s have a look at the complexity analysis of the above solution:
The time complexity of the solution above is
word1
.
word2
.
The space complexity of the solution above is
Free Resources