How to Solve “Merge Strings Alternately” on LeetCode with JavaScript
LeetCode’s “Merge Strings Alternately” problem is a fantastic challenge for sharpening your string manipulation skills. In this blog post, we’ll walk through the problem, discuss the solution approach, and write clean, efficient JavaScript code. Plus, check out my accompanying video tutorial here on David Mascia Tutorials for a step-by-step explanation!
Problem Description
The problem is simple: Given two strings, word1 and word2, merge them by alternating characters from each string. If one string is longer than the other, append the remaining characters of the longer string at the end.
Example
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"Approach to Solve the Problem
Key Observations:
1. The merged string alternates between characters from word1 and word2.
2. Once one string is exhausted, the remaining characters of the longer string are appended.
Plan:
The key to solving this problem is:
1. Iterating through both strings simultaneously.
2. Appending characters alternately from word1 and word2.
3. Adding any leftover characters from the longer string after the iteration.
JavaScript Solution
Here’s the implementation:
function mergeAlternately(word1: string, word2: string): string {
let word1Length = word1.length;
let word2Length = word2.length;
let word1StartIdx = 0;
let word2StartIdx = 0;
let result = "";
while (word1StartIdx < word1Length && word2StartIdx < word2Length) {
result += word1[word1StartIdx++]
result += word2[word2StartIdx++]
}
while (word1StartIdx < word1Length) {
result += word1[word1StartIdx++]
}
while (word2StartIdx < word2Length) {
result += word2[word2StartIdx++]
}
return result;
};
// Example Usage
console.log(mergeAlternately("abc", "pqr")); // Output: "apbqcr"
console.log(mergeAlternately("ab", "pqrs")); // Output: "apbqrs"
console.log(mergeAlternately("abcd", "pq")); // Output: "apbqcd"Complexity Analysis
• Time Complexity: O(n), where n is the combined length of word1 and word2. Each character is processed once.
• Space Complexity: O(n), where n is the length of the merged string.
Watch the Full Tutorial!
Want a more detailed walkthrough? Watch my video tutorial on David Mascia Tutorials here, where I dive deeper into the code and explain the logic step by step.
Final Thoughts
This problem is a great introduction to string manipulation in JavaScript. By practicing problems like this, you’ll improve your problem-solving skills and prepare for technical interviews.
If you found this blog helpful, don’t forget to like, share, and check out more of my tutorials on Medium and YouTube! 🚀
