Misa's Blog

LeetCode #1 Merge Strings Alternately

So, it's been a long time since I last did LeetCode or other programming challenges. My brain has become dull from lack of use. So, I decided to start doing programming challenges on LeetCode again and made a new account

https://leetcode.com/u/LLENN08/

No AI, no pressure. I'm doing these just for fun. I'll try to solve the challenge by myself. No matter how much time it takes to solve, one hours, two hours, or even one day. I'll take as much time as I need to solve the problem given.

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

SOLUTION

my idea was simple, just using loops to insert each character from word2 to word1. if length word2 more bigger than word1, adding the character remaining to word1

class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        bool q = false;
        int difference;
        int i = 0;
        int length;
        
        if(word1.length() > word2.length()){
            length = word2.length();
        } else{
            length = word1.length();
            q = true;
            difference = word2.length()-word1.length();
        }
   
        for (int j = 0; j < length; j++){
           word1.insert(j+1+i, string(1,word2[j]));
            i++; 
        }

         if (q){
            word1.insert(word1.end(), word2.end()-difference, word2.end());
        }

        return word1;
    }
};

Screenshot of an accepted LeetCode submission by user LLENN08, showing 108 out of 108 test cases passed. The runtime is 0 ms, beating 100% of submissions, while memory usage is 8.85 MB, beating 9.78%. Submission was made on July 8, 2025, at 23:59.

The runtime is pretty neat and close to zero but it eats up a lot of memory, lol. my code really ugly, pretty sure no one company wanna hired me.

I haven’t found any good alternative solutions yet, but I’ll think about it later.