π Problem Details
- Title:
1768. Merge Strings Alternately
- Link: https://leetcode.com/problems/merge-strings-alternately/
- Difficulty: Easy
- Tags/Categories: Strings Two-Pointers
input strings
word1
andword2
merge the strings by adding letters in alternating order, starting withword1
πWhat Were My Initial Thoughts?
- two pointers approach:
- i to iterate through word1
- j to iterate through word2
π‘ Explanation of Solution
same as intuition:
- use if statements inside the while loop to ensure that the i and j pointers are in bounds before pushing them to result
β Complexity Analysis
Time Complexity: O(n + m)
Space Complexity: O(n + m) for result storage
π» Implementation of Solution
class Solution {
public:
string mergeAlternately(string word1, string word2) {
int m = word1.size();
int n = word2.size();
int i = 0, j = 0;
string result = "";
while(i < m || j < n) {
if(i < m) result.push_back(word1[i++]);
if(j < n) result.push_back(word2[j++]);
}
return result;
}
};