Merge Strings Alternately , UBER

645
Apr 18, 2023
//*** ASKED BY UBER 
// T.C AND S.C: O(max(n,m))
// please do upvote
class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        int n = size(word1);  //  find the size of each string
        int m = size(word2);
        int t = min(n,m);    // take minimum of them , because  we first ,run a loop with same size of the string  ,
        
             string ans ="";
             int i ;
        for( i=0; i<t; i++){
          ans.push_back(word1[i]);
          ans.push_back(word2[i]);
        }
		// if there is any remaining string we append them into ans
        if(i<n){
            while(i<n){
                ans.push_back(word1[i]);
                i++;
            }
        }
        if(i<m){
            while(i<m){
                ans.push_back(word2[i]);
                i++;
            }
        }
        return ans;
    }
};
Comments (2)