Calle's Blog

Let's do some leet code 1768

Let's start with 1768 - Merging Two Strings Alternately

1768

This is a basic problem, where we are given two strings word1 and word2. We are asked to merge the strings in alternating order, starting with word1. Then return the merged string. I will sovle this in C++, because why not.

class Solution {
    public:
        string mergeAlternately(string word1, string word2) {
            
            // First we need two variables to hold the size of the strings
            int sizeWordOne = word1.size();
            int sizeWordTwo = word2.size();

            std::string result = "";
           
            // We need to add alternatively, and loop for the longest string
            for(int i = 0; i < max(sizeWordOne, sizeWordTwo); i ++) {
                if(i < sizeWordOne) {
                    result.push_back(word1[i]);
                }
                if(i < sizeWordTwo) {
                    result.push_back(word2[i]);
                }
            }
         return result;
    }
}

Alrighty, we pass all the tests, we can also make the if's a bit more clean, becuase why not.

class Solution {
    public:
        string mergeAlternately(string word1, string word2) {
            
            // First we need two variables to hold the size of the strings
            int sizeWordOne = word1.size();
            int sizeWordTwo = word2.size();

            std::string result = "";
           
            // We need to add alternatively, and loop for the longest string
            for(int i = 0; i < max(sizeWordOne, sizeWordTwo); i ++) {
                (i < sizeWordOne) ? result.push_back(word1[i]) : void();
                
                (i < sizeWordTwo) ? result.push_back(word2[i]) : void();
                
            }
         return result;
    }
};

So what about the complexity?

Time Complexity: O(m+n)

This is becuase we iterate over both words, word1 and word2 then push the letters into the result string.

Space Complexity: O(1)

The strings will take constant space