LeetCode 1768: Merge Strings Alternately Solution

Master LeetCode problem 1768 (Merge Strings Alternately), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1768. Merge Strings Alternately

Problem Explanation

Explanation

To solve this problem, we can iterate over both input strings simultaneously and merge them by adding letters in alternating order. We can keep track of the current index in both strings and append the characters to the result string accordingly. If one string is longer than the other, we can simply append the remaining characters to the result string.

Algorithmic Idea

  1. Initialize two pointers i and j for word1 and word2 respectively.
  2. Iterate over both strings and merge them by adding letters in alternating order.
  3. If one string is longer than the other, append the remaining characters to the result string.
  4. Return the merged string.

Time Complexity

The time complexity of this approach is O(n), where n is the maximum length of word1 and word2.

Space Complexity

The space complexity is also O(n) since we are using a StringBuilder to store the merged string.

Solution Code

class Solution {
    public String mergeAlternately(String word1, String word2) {
        StringBuilder result = new StringBuilder();
        int i = 0, j = 0;
        
        while (i < word1.length() || j < word2.length()) {
            if (i < word1.length()) {
                result.append(word1.charAt(i));
                i++;
            }
            if (j < word2.length()) {
                result.append(word2.charAt(j));
                j++;
            }
        }
        
        return result.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1768 (Merge Strings Alternately)?

This page provides optimized solutions for LeetCode problem 1768 (Merge Strings Alternately) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1768 (Merge Strings Alternately)?

The time complexity for LeetCode 1768 (Merge Strings Alternately) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1768 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1768 in Java, C++, or Python.

Back to LeetCode Solutions