You are given two strings
Return the merged string.
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1 : a b c
word2 : p p r
merged: apbqcr
Output: "apbqrs"
Explanation: The merged string will be merged as so:
word1 : a b
word2 : p p r s
merged: apbqrs
Output: "apbqcd"
Explanation: The merged string will be merged as so:
word1 : a b c d
word2 : p p
merged: apbqcd
Constraints:
1 <= word1.length, word2.length <= 100 word1 andword2 consist of lowercase English letters.
Contents
Solution 1 - Using two pointers
In this approach, we will use pointers to iterate through
Implementation steps:
-
Create three variables
i to iterate throughword1 ,j to iterate throughword2 , andresult asStringBuilder to capture the result. -
Then, loop through characters of
word1 andword2 , whilei don't go out of bounds ofword1 , andj don't go out of bounds ofword2 :-
Add character at
ith position from input string toword1 toresult , and incrementi . -
Add character at
jth position from input string toword2 toresult , and incrementj .
-
Add character at
-
At the end, we may still have left with some characters either in
word1 orword2 , if they are not equal length strings. Check ifi did not reach the end ofword1 , then add remaining characters fromword1 toresult , and ifj did not reach the end ofword2 , then add remaining characters fromword2 toresult .
Complexity Analysis:
Time complexity: Above code runs in O(max(m,n)) time where
Space complexity: O(1) if we ignore result string, otherwise O(m +n) for the result string.
Above implementations source code can be found at