Post

Leetcode 1768. Merge Strings Alternately

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.

Description

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"
  • 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"
  • 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"
  • 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.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    # Iteration
    # Time Complexity: BigO(N)
    # Space Complexity: BigO(1)
    def mergeAlternately(self, word1: str, word2: str) -> str:
        l1, l2 = len(word1), len(word2)
        max = l1 if l1 > l2 else l2
        res = ""
        for i in range(max):
            if l1 > i:
                res += word1[i]
            if l2 > i:
                res += word2[i]

        return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
 * Do not return anything, modify nums in-place instead.
 * Iteration
 * Time Complexity: BigO(N)
 * Space Complexity: BigO(1)
 */
function mergeAlternately(word1: string, word2: string): string {
  let maxLength = word1.length > word2.length ? word1.length : word2.length;
  let res = "";
  for (let i = 0; i < maxLength; i++) {
    if (word1[i]) res += word1[i];
    if (word2[i]) res += word2[i];
  }
  return res;
}
This post is licensed under CC BY 4.0 by the author.