Skip to content

Instantly share code, notes, and snippets.

@mtzfox
Last active July 12, 2023 06:08
Show Gist options
  • Save mtzfox/513f015547fb09b53eee844bd8255b07 to your computer and use it in GitHub Desktop.
Save mtzfox/513f015547fb09b53eee844bd8255b07 to your computer and use it in GitHub Desktop.
Merge two strings with alternating letters: abc, xyz => axbycz
function mergeAlternately(word1, word2) {
// get max length of each word
let m = word1.length,
n = word2.length,
// starting word
result = '';
// if either index is less than word length, add current letter to result
for (i = 0; i < Math.max(m, n); i++) {
if (i < m) {
result += word1[i];
}
if (i < n) {
result += word2[i];
}
}
return result;
}
mergeAlternately('abc', 'xyz');
function mergeAlternately(word1, word2) {
// get max length of each word
let m = word1.length,
n = word2.length,
// starting word and indices
result = '',
i = 0,
j = 0;
// if either index is less than word length,
// add current letter to result then add to that index
while (i < m || j < n) {
if (i < m) {
result += word1[i];
i++;
}
if (j < n) {
result += word2[j];
j++;
}
}
return result;
}
mergeAlternately('abc', 'xyz');
@mtzfox
Copy link
Author

mtzfox commented Jul 12, 2023

Leetcode 1768. Merge Strings Alternately

Thought process

  1. Get length of each word and start two indexes at 0, set result string variable
  2. While loop checks if either index is less, if so, add current letter (starting with first word) and move index forward
  3. Return result

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment