Merge Strings Alternately , UBER

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2023-04-18Added By Anonymous
Source: Link

Company: Uber
Role: unknown
Interview Stage: unknown
Location: unknown
Year: unknown

Original Post Content:

//*** 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