Talentd
FleetCode
Make and follow sheets.Sign in

Merge Strings Alternately solution and explanation

EasyStringTwo Pointers5 min read82.1% acceptanceUpdated 9 Apr 2026
Merge Strings Alternately - Leetcode 1768 - PythonNeetCodeIO · 4:22 · 47K viewsWatch on YouTube
9 more videos on this problem
  1. Merge Strings Alternately - Leetcode 1768 - PythonNeetCodeIO · 4:22 · 47K views
  2. Merge Strings Alternately - Leetcode 1768 - Arrays & Strings (Python)Greg Hogg · 7:07 · 39K views
  3. Merge Strings Alternately - LeetCode #1768 - Python, JavaScript, Java and C++CodingNinja · 4:02 · 17K views
  4. Merge Strings Alternately - LeetCode 1768 - Python #leetcode #leetcode75Deepti Talesra · 6:09 · 7K views
  5. Merge strings alternately | Leetcode 1768Technosage · 9:09 · 5K views
  6. LeetCode 1768. Merge String Alternately, JavaScriptPatrick Codes · 4:17 · 605 views
  7. 1768. Merge Strings Alternately (Leetcode Easy)Programming Live with Larry · 3:09 · 565 views
  8. 1768. Merge Strings Alternately | Leetcode 75 | O(n) | StringsRapid Syntax · 7:39 · 538 views
  9. Leetcode | Easy | 1768. Merge Strings Alternately |Two Pointers | Time: O(N) | JavascriptSoftware Interviews Prep · 4:50 · 312 views
  10. Merge Strings Alternately - LeetCode 1768 (Easy Solution) - PythonCode Kaizen · 7:07 · 257 views

The problem

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.

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 and word2 consist of lowercase English letters.

Approach overview

Problem Overview: You are given two strings and must build a new string by alternating characters from each. Start with the first character of word1, then word2, and continue until one string runs out. Append the remaining characters from the longer string at the end.

Approach 1: Iterative Merge with Indices (O(n + m) time, O(1) extra space)

This approach walks through both strings using two indices. Start with i = 0 for word1 and j = 0 for word2. On each step, append word1[i] if i is still within bounds, then append word2[j] if j is valid. Increment the corresponding pointer after each append. The process continues until both pointers reach the end of their strings.

The key insight is that alternating order is deterministic. There is no need for extra data structures or backtracking. You simply iterate forward and append characters as you go. Once one string is exhausted, the loop still checks the other pointer and continues appending remaining characters.

This pattern is essentially a simplified form of the two pointers technique where each pointer advances independently through its sequence. Because each character is processed exactly once, the runtime is O(n + m) where n and m are the lengths of the two strings. Extra space remains O(1) aside from the output buffer. This is the most common and practical solution and is supported in C, C++, Java, Python, C#, and JavaScript.

Approach 2: Recursive Approach (O(n + m) time, O(n + m) space)

The recursive version models the alternating merge as repeated subproblems. At each step, take the first character of word1 and the first character of word2, append them, and recursively process the remaining substrings. If either string becomes empty, return the other string as the base case.

The recursion naturally enforces the alternating pattern because every call consumes one character from each string. Conceptually this solution is elegant: each call reduces the problem size until one string is exhausted.

However, recursion adds call stack overhead. Each recursive call stores state on the stack, leading to O(n + m) auxiliary space in the worst case. For languages without tail call optimization, this approach is less memory‑efficient than iteration. The logic still revolves around basic string operations such as slicing or indexing.

Recommended for interviews: The iterative two‑pointer solution is what interviewers expect. It demonstrates clear control of indices, efficient iteration, and awareness of linear time complexity. Showing the recursive idea can illustrate problem decomposition, but the iterative approach better reflects practical coding patterns for two pointer style string problems.

Approach 1: Iterative Merge with Indices

This approach uses a loop to iterate through the characters in the strings by index. We initiate a loop for the length of the shorter string, adding characters alternately from each string to a result. Once the loop ends, we append the remaining part of the longer string.

def merge_alternately(word1: str, word2: str) -> str:
    result = []
    i, j = 0, 0
    while i < len(word1) and j < len(word2):
        result.append(word1[i])
        result.append(word2[j])
        i += 1
        j += 1
    result.append(word1[i:])
    result.append(word2[j:])
    return ''.join(result)

print(merge_alternately("abc", "pqr"))
public class MergeStrings {
    public static String mergeAlternately(String word1, String word2) {
        StringBuilder result = new StringBuilder();
        int i = 0, j = 0;
        while (i < word1.length() && j < word2.length()) {
            result.append(word1.charAt(i++));
            result.append(word2.charAt(j++));
        }
        result.append(word1.substring(i));
        result.append(word2.substring(j));
        return result.toString();
    }

    public static void main(String[] args) {
        String word1 = "abc";
        String word2 = "pqr";
        System.out.println(mergeAlternately(word1, word2));
    }
}
#include <iostream>
#include <string>

std::string mergeAlternately(const std::string& word1, const std::string& word2) {
    std::string result;
    int i = 0, j = 0;
    while (i < word1.size() && j < word2.size()) {
        result += word1[i++];
        result += word2[j++];
    }
    result += word1.substr(i);
    result += word2.substr(j);
    return result;
}

int main() {
    std::string word1 = "abc";
    std::string word2 = "pqr";
    std::cout << mergeAlternately(word1, word2) << std::endl;
    return 0;
}
function mergeAlternately(word1, word2) {
    let result = '';
    let i = 0, j = 0;
    while (i < word1.length && j < word2.length) {
        result += word1[i++];
        result += word2[j++];
    }
    result += word1.substring(i);
    result += word2.substring(j);
    return result;
}

console.log(mergeAlternately("abc", "pqr"));
#include <stdio.h>
#include <string.h>

char* mergeAlternately(char* word1, char* word2) {
    int len1 = strlen(word1);
    int len2 = strlen(word2);
    int maxLength = len1 + len2;
    char* result = (char*)malloc((maxLength + 1) * sizeof(char));
    int index = 0, i = 0, j = 0;

    while (i < len1 && j < len2) {
        result[index++] = word1[i++];
        result[index++] = word2[j++];
    }
    while (i < len1) {
        result[index++] = word1[i++];
    }
    while (j < len2) {
        result[index++] = word2[j++];
    }
    result[index] = '\0';

    return result;
}

int main() {
    char word1[] = "abc";
    char word2[] = "pqr";
    char* merged = mergeAlternately(word1, word2);
    printf("%s\n", merged);
    free(merged);
    return 0;
}
using System;

class MergeStrings {
    public static string MergeAlternately(string word1, string word2) {
        var result = new System.Text.StringBuilder();
        int i = 0, j = 0;
        while (i < word1.Length && j < word2.Length) {
            result.Append(word1[i++]);
            result.Append(word2[j++]);
        }
        result.Append(word1.Substring(i));
        result.Append(word2.Substring(j));
        return result.ToString();
    }

    public static void Main() {
        string word1 = "abc";
        string word2 = "pqr";
        Console.WriteLine(MergeAlternately(word1, word2));
    }
}

The function merge_alternately merges the strings using two indices. It appends characters alternately to a list and concatenates remaining parts of the longer string if one finishes earlier. Finally, the merged result is constructed with join.

Complexity

Time Complexity: O(n + m), where n and m are the lengths of the two strings.
Space Complexity: O(n + m) for the resulting list.

Try this approach in the editor

Approach 2: Recursive Approach

This approach uses recursion to merge the strings by alternating characters. It utilizes recursive calls to handle the process of alternately taking characters from each string, ending the recursion once one of the strings is fully consumed. The remaining part of the longer string is then joined directly to the result.

def merge_alternately(word1: str, word2: str) -> str:
    if not word1:
        return word2
    if not word2:
        return word1
    return word1[0] + word2[0] + merge_alternately(word1[1:], word2[1:])

print(merge_alternately("abc", "pqr"))

This recursive function merge_alternately checks if either string is empty. If so, it returns the remaining part of the other string. Otherwise, it returns the first character of each string concatenated with a recursive call using the rest of the strings.

Complexity

Time Complexity: O(n + m), where n and m are the lengths of the two strings.
Space Complexity: O(n + m) for call stack and resulting string in the worst case.

Try this approach in the editor

Approach 3: Direct Simulation

We traverse the two strings word1 and word2, take out the characters one by one, and append them to the result string. The Python code can be simplified into one line.

The time complexity is O(m + n), where m and n are the lengths of the two strings respectively. Ignoring the space consumption of the answer, the space complexity is O(1).

function mergeAlternately(word1: string, word2: string): string {
    const ans: string[] = [];
    const [m, n] = [word1.length, word2.length];
    for (let i = 0; i < m || i < n; ++i) {
        if (i < m) {
            ans.push(word1[i]);
        }
        if (i < n) {
            ans.push(word2[i]);
        }
    }
    return ans.join('');
}
func mergeAlternately(word1 string, word2 string) string {
	m, n := len(word1), len(word2)
	ans := make([]byte, 0, m+n)
	for i := 0; i < m || i < n; i++ {
		if i < m {
			ans = append(ans, word1[i])
		}
		if i < n {
			ans = append(ans, word2[i])
		}
	}
	return string(ans)
}
impl Solution {
    pub fn merge_alternately(word1: String, word2: String) -> String {
        let s1 = word1.as_bytes();
        let s2 = word2.as_bytes();
        let n = s1.len().max(s2.len());
        let mut res = vec![];
        for i in 0..n {
            if s1.get(i).is_some() {
                res.push(s1[i]);
            }
            if s2.get(i).is_some() {
                res.push(s2[i]);
            }
        }
        String::from_utf8(res).unwrap()
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Iterative Merge with Indices

Time Complexity: O(n + m), where n and m are the lengths of the two strings.
Space Complexity: O(n + m) for the resulting list.

Recursive Approach

Time Complexity: O(n + m), where n and m are the lengths of the two strings.
Space Complexity: O(n + m) for call stack and resulting string in the worst case.

Direct Simulation–

Complexity analysis

ApproachTimeSpaceWhen to Use
Iterative Merge with IndicesO(n + m)O(1)General case. Most efficient and interview‑preferred solution.
Recursive ApproachO(n + m)O(n + m)Useful for demonstrating recursion and problem decomposition.

Frequently asked questions

Is Merge Strings Alternately easy or hard?

Merge Strings Alternately is classified as an Easy problem on LeetCode with a high acceptance rate above 80%. It mainly tests basic string traversal, pointer management, and careful handling of leftover characters.

Merge Strings Alternately Python/Java solution

In Python or Java, iterate with two indices and append characters to a result builder. Python typically uses a list or string concatenation with join, while Java uses StringBuilder for efficient appends. Both implementations run in O(n + m) time.

How to solve Merge Strings Alternately in O(n)?

Use two indices starting at the beginning of each string. Append characters alternately while incrementing the pointers. Continue until both indices reach the end, appending leftover characters if one string is longer. This ensures each character is visited only once, giving O(n + m) time complexity.

What is the best approach for Merge Strings Alternately?

The best approach uses two pointers (or indices) to iterate through both strings and append characters alternately. Each pointer advances independently and remaining characters from the longer string are appended at the end. This runs in O(n + m) time with O(1) extra space.

Is Merge Strings Alternately asked at Google/Amazon/Meta?

Merge Strings Alternately appears in coding interview preparation sets and is commonly used as an introductory string or two‑pointer problem. Similar alternating merge patterns show up in interviews at companies like Amazon and Google to test basic string manipulation and pointer control.

What data structure is used in Merge Strings Alternately?

The problem mainly uses basic string operations and the two‑pointer technique. Some implementations use a mutable string builder or character array to efficiently append characters during iteration.

What is the time complexity of Merge Strings Alternately?

The optimal solution processes each character from both strings exactly once. If the string lengths are n and m, the time complexity is O(n + m). Space complexity is O(1) excluding the output string.

Comments

Now write it yourselfClose this page and solve Merge Strings Alternately in the editor, without looking.
Practise Merge Strings Alternately