Skip to content

Commit d4dee29

Browse files
committed
Update: 1768 Merge Strings Alternately - TypeScript & JavaScript
1 parent dbc0ef2 commit d4dee29

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
// Time complexity: O(n)
2+
// Space complexity: O(n)
3+
14
var mergeAlternately = function (word1, word2) {
2-
let res = '';
5+
const buffer = [];
36

47
for (let i = 0; i < word1.length || i < word2.length; i++) {
5-
if (i < word1.length) res += word1[i];
6-
if (i < word2.length) res += word2[i];
8+
if (i < word1.length) buffer.push(word1[i]);
9+
if (i < word2.length) buffer.push(word2[i]);
710
}
811

9-
return res;
12+
return buffer.join('');
1013
};
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
// Time complexity: O(n)
2+
// Space complexity: O(n)
3+
14
function mergeAlternately(word1: string, word2: string): string {
2-
let res = '';
5+
const buffer: Array<string> = [];
36

47
for (let i = 0; i < word1.length || i < word2.length; i++) {
5-
if (i < word1.length) res += word1[i];
6-
if (i < word2.length) res += word2[i];
8+
if (i < word1.length) buffer.push(word1[i]);
9+
if (i < word2.length) buffer.push(word2[i]);
710
}
811

9-
return res;
12+
return buffer.join('');
1013
}

0 commit comments

Comments
 (0)