Intuition
We want to weave two strings together by picking characters alternately—first from word1, then from word2, and so on.
If one string runs out of characters before the other, we simply append the remaining characters of the longer string to the result.
Think of it like a zipper:
- Take one character from word1
- Take one from word2
- Repeat until both strings are exhausted
Algorithm
Initialize two pointers i and j for word1 and word2.
-
Loop while at least one pointer is still within its string:
- If i is within bounds, append word1.charAt(i) and increment i.
- If j is within bounds, append word2.charAt(j) and increment j.
Return the merged string.
This ensures:
Characters are added alternately.
Any leftover characters from the longer string are appended at the end.
Complexities
Time Complexity:
O(n+m)
where n is the length of word1 and m is the length of word2.
Each character from both strings is processed exactly once.
Space Complexity:
O(n+m)
for storing the merged result.
class Solution {
public String mergeAlternately(String word1, String word2) {
int l1 = word1.length();
int l2 = word2.length();
int i = 0, j = 0;
String res = "";
while(i<l1 || j<l2){
if(i<l1)
res = res + word1.charAt(i++);
if(j<l2)
res = res + word2.charAt(j++);
}
return res;
}
}
Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀
Top comments (0)