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 <= 100word1 and word2 consist of lowercase English letters.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.
The function mergeAlternately initializes by determining the lengths of the input strings. It allocates memory for the result string that can accommodate both input strings' lengths combined. It uses two indices to add characters alternately from each input string. When one string ends, the remaining characters of the other string are appended to the result. Finally, the function returns the merged string.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n + m), where n and m are the lengths of the two strings.
Space Complexity: O(n + m) for the resulting string.
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.
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.
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.
| Approach | Complexity |
|---|---|
| Iterative Merge with Indices | Time Complexity: O(n + m), where n and m are the lengths of the two strings. |
| Recursive Approach | Time Complexity: O(n + m), where n and m are the lengths of the two strings. |
Merge Strings Alternately - Leetcode 1768 - Python • NeetCodeIO • 34,388 views views
Watch 9 more video solutions →Practice Merge Strings Alternately with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor