Merge Strings Alternately
Leetcode Daily Challenge (18th April, 2023)
Problem Statement:-
You are given two strings word1
and word2
. Merge the strings by adding letters in alternating order, starting with word1
. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return the merged string.
Link: https://leetcode.com/problems/merge-strings-alternately/description/
Problem Explanation with examples:-
Example 1
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r
Example 2
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1: a b
word2: p q r s
merged: a p b q r s
Example 3
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1: a b c d
word2: p q
merged: a p b q c d
Constraints
1 <= word1.length, word2.length <= 100
word1
andword2
consist of lowercase English letters.
Intuition:-
It's a simple string concatenation problem where iterating both strings in parallel is the simplest solution.
The only thing to watch out for is the case where one string is longer than the other. In that case, we need to append the remaining characters of the longer string to the answer.
Solution:-
Initialize two pointers i and j to 0.
Initialize an empty string ans.
While i < len(word1) and j < len(word2), append word1[i] and word2[j] to ans and increment i and j by 1.
Then for the extra characters case, append the remaining characters of word1 to ans if i < len(word1) and the remaining characters of word2 to ans if j < len(word2) using while loops independently.
Return ans.
Code:-
JAVA Solution
class Solution {
public String mergeAlternately(String word1, String word2) {
int i = 0;
int j = 0;
StringBuilder ans = new StringBuilder();
while (i < word1.length() && j < word2.length()) {
ans.append(word1.charAt(i)).append(word2.charAt(j));
i++;
j++;
}
while (i < word1.length()) {
ans.append(word1.charAt(i));
i++;
}
while (j < word2.length()) {
ans.append(word2.charAt(j));
j++;
}
return ans.toString();
}
}
Python Solution
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
i = 0
j = 0
ans = ''
while i < len(word1) and j < len(word2):
ans += word1[i]+word2[j]
i += 1
j += 1
while i < len(word1):
ans += word1[i]
i += 1
while j < len(word2):
ans += word2[j]
j += 1
return ans
Complexity Analysis:-
TIME:-
The time complexity of the given Python code is O(n) where n is the length of the longer string between word1 and word2 because we iterate through both strings in parallel and then append the remaining characters of the longer string to ans.
SPACE:-
The space complexity of the code is also O(1) because we only use constant space to store the pointers i, j apart from the answer string ans.