DEV Community

Md. Shafiqul Islam
Md. Shafiqul Islam

Posted on

Merge Strings Alternately in javascript

Image description
After a long time, I'm back to solving problems in the LeetCode 75 series. Today, I solved the first problem, which was easy but had some tricky corner cases. I'd like to share how I approached this 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.

Example:
Input: word1 = "abc",
word2 = "pqr"
Output: "apbqcr"

I divided my solution into three parts:

  • Logic check (corner case handling)
  • Using a for loop
  • Appending the final string

Logic check: First, I checked which word had the smallest length. I then iterated the loop based on this smallest length. If one word was longer than the other, I appended the remaining characters from the longer word to the end of the string.

Using a loop: I used a loop to alternate and merge characters from each string.

Appending the final string: Finally, I combined the strings and returned the result.

var mergeAlternately = function (word1, word2) {
  let str = "";

  if (word2.length > word1.length) {
    for (let i = 0; i < word1.length; i++) {
      str = str + word1[i] + word2[i];
    }
    str = str + word2.substring(word1.length);
  } else if (word1.length > word2.length) {
    for (let i = 0; i < word2.length; i++) {
      str = str + word1[i] + word2[i];
    }
    str = str + word1.substring(word2.length);
  } else {
    for (let i = 0; i < word1.length; i++) {
      str = str + word1[i] + word2[i];
    }
  }
  return str;
};

console.log("result", mergeAlternately("abcd", "pq"));

result: apbqcd

Enter fullscreen mode Exit fullscreen mode

If you have better solutions or ideas, feel free to share with me.

Top comments (2)

Collapse
 
pengeszikra profile image
Peter Vivo • Edited

Take a look this one, `[...first] split string to characters, then mapping to char pair at the end added that is left.

javascript
/** @type (first: string, second: string) => string */
const merge2 = (first, second) => [...first]
.map((char, index) => char + (
second[index]
? second[index]
: ""
))
.join('')
+ second.slice(first.length);

strange the code formating don't work fine on this comment

Collapse
 
shafiqbd profile image
Md. Shafiqul Islam

But there is missing of corner case.