Have you ever played a game with a friend where you both take turns? Maybe you’ve played a board game where each of you moves a piece one after the other. Or perhaps you've made a friendship bracelet, alternating colors with each knot. This idea of taking turns is not just fun; it can also be a great way to solve problems in programming. One such problem is merging strings alternately.
Imagine you have two pieces of rope, each a different color. You twist them together, one loop from the red rope, one loop from the blue, and continue until they’re intertwined.
By the end, you have a beautiful pattern made from both colors.
This is similar to what we’ll do with two strings in this problem: we’ll combine them by taking one character from each, creating a new string that includes both.
Problem statement
You are given two strings, word1 and word2. Your task is to merge these strings by alternating characters from each. If one string is longer than the other, append the remaining characters of the longer string at the end.
Sample input
1word1 = "abc"
2word2 = "pqr"
Sample output
1"apbqcr"
Understanding the problem
The concept of merging strings alternately is similar to taking turns in a game. You take one step, then your friend takes one step, and so on. This back-and-forth continues until both of you have taken all your steps. In the context of strings, we’re simply taking one character from word1, then one from word2, and repeating this until we’ve used up all characters from both strings.
But what if one string is longer than the other? Just like in a game where one player has more turns left, you continue with the remaining characters from the longer string after the shorter one is exhausted. The key is to handle both strings fairly, making sure no characters are left behind.
Brute force approach
The simplest way to solve this problem is by using a loop to go through both strings at the same time. For each step in the loop, you take one character from word1 and one from word2, adding them to your result. If you reach the end of one string before the other, you just add the remaining characters from the longer string to the result.
A smarter approach
A more efficient way to solve the problem is by looping through the strings while keeping track of your position in each. This way, you can easily add characters alternately and handle the remaining characters from the longer string once one string is fully processed. This approach is both simple and efficient, making it ideal for this problem.
Pseudocode
Let’s break down the solution into simple steps that even a beginner can follow:
- Create an empty string called result to store the merged characters.
- Initialize a loop that runs while there are characters left in either word1 or word2.
- For each iteration of the loop:
- If there are characters left in word1, add the next character to result.
- If there are characters left in word2, add the next character to result.
- After the loop ends, result will contain the merged string.
- Return result.
Python code
Let’s start with a simple approach using Python:
1def merge_alternately(word1, word2):
2 result = ""
3 i, j = 0, 0
4
5 while i < len(word1) or j < len(word2):
6 if i < len(word1):
7 result += word1[i]
8 i += 1
9 if j < len(word2):
10 result += word2[j]
11 j += 1
12
13 return result
Explanation
- We initialize an empty string result to hold the merged characters.
- We use two pointers, i and j, to keep track of our position in word1 and word2.
- The loop continues until we’ve processed all characters in both strings.
- Inside the loop, we add one character from word1 (if available) and one from word2 (if available) to result.
- Finally, we return the merged string.
Java code
1public class MergeStrings {
2 public String mergeAlternately(String word1, String word2) {
3 StringBuilder result = new StringBuilder();
4 int i = 0, j = 0;
5
6 while (i < word1.length() || j < word2.length()) {
7 if (i < word1.length()) {
8 result.append(word1.charAt(i));
9 i++;
10 }
11 if (j < word2.length()) {
12 result.append(word2.charAt(j));
13 j++;
14 }
15 }
16
17 return result.toString();
18 }
19}
C++ code
1#include <string>
2
3std::string mergeAlternately(std::string word1, std::string word2) {
4 std::string result;
5 int i = 0, j = 0;
6
7 while (i < word1.length() || j < word2.length()) {
8 if (i < word1.length()) {
9 result += word1[i];
10 i++;
11 }
12 if (j < word2.length()) {
13 result += word2[j];
14 j++;
15 }
16 }
17
18 return result;
19}
Explanation
- The logic in Java and C++ is similar to the Python version.
- We use a loop to alternately add characters from word1 and word2 to result.
- Once the loop is complete, the merged string is returned.
Efficient approach
The brute force approach is already quite efficient with a time complexity of O(N), where N is the combined length of the two strings. However, we can streamline the solution by directly appending any remaining characters from the longer string once the other string is fully processed.
Python code
1def merge_alternately(word1, word2):
2 result = []
3 i = 0
4
5 while i < len(word1) and i < len(word2):
6 result.append(word1[i])
7 result.append(word2[i])
8 i += 1
9
10 result.append(word1[i:])
11 result.append(word2[i:])
12
13 return "".join(result)
Explanation
- We use a list result to store the characters, which makes appending more efficient.
- We alternate between characters from word1 and word2 while both have characters left.
- Once we reach the end of one string, we append the remaining characters from the other string.
- The final string is created by joining the list of characters.
Java code
1public class MergeStrings {
2 public String mergeAlternately(String word1, String word2) {
3 StringBuilder result = new StringBuilder();
4 int i = 0;
5
6 while (i < word1.length() && i < word2.length()) {
7 result.append(word1.charAt(i));
8 result.append(word2.charAt(i));
9 i++;
10 }
11
12 result.append(word1.substring(i));
13 result.append(word2.substring(i));
14
15 return result.toString();
16 }
17}
C++ code
1#include <string>
2
3std::string mergeAlternately(std::string word1, std::string word2) {
4 std::string result;
5 int i = 0;
6
7 while (i < word1.length() && i < word2.length()) {
8 result += word1[i];
9 result += word2[i];
10 i++;
11 }
12
13 result += word1.substr(i);
14 result += word2.substr(i);
15
16 return result;
17}
Explanation
- This efficient approach reduces unnecessary checks and directly appends remaining characters from the longer string.
- The time complexity remains O(N), but the code is cleaner and more optimized.
Conclusion
Merging strings alternately is like weaving two different threads into one strong rope. It’s a simple yet effective way to combine two sequences. Whether you’re solving problems in Python, Java, or C++, understanding the logic behind merging strings helps you think about how to handle sequences efficiently.
Frequently Asked Questions
Sign-in First to Add Comment
Leave a comment 💬