mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 01:18:23 +08:00

* chore: Switch to Node 20 + Vitest * chore: migrate to vitest mock functions * chore: code style (switch to prettier) * test: re-enable long-running test Seems the switch to Node 20 and Vitest has vastly improved the code's and / or the test's runtime! see #1193 * chore: code style * chore: fix failing tests * Updated Documentation in README.md * Update contribution guidelines to state usage of Prettier * fix: set prettier printWidth back to 80 * chore: apply updated code style automatically * fix: set prettier line endings to lf again * chore: apply updated code style automatically --------- Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
48 lines
1.5 KiB
JavaScript
48 lines
1.5 KiB
JavaScript
// Alternative arrange the two given strings in one string in O(n) time complexity.
|
|
|
|
// Problem Source & Explanation: https://www.geeksforgeeks.org/alternatively-merge-two-strings-in-java/
|
|
|
|
/**
|
|
* Alternative arrange the two given strings in one string in O(n) time complexity.
|
|
* @param {String} str1 first input string
|
|
* @param {String} str2 second input string
|
|
* @returns `String` return one alternative arrange string.
|
|
*/
|
|
const AlternativeStringArrange = (str1, str2) => {
|
|
// firstly, check that both inputs are strings.
|
|
if (typeof str1 !== 'string' || typeof str2 !== 'string') {
|
|
return 'Not string(s)'
|
|
}
|
|
|
|
// output string value.
|
|
let outStr = ''
|
|
|
|
// get first string length.
|
|
const firstStringLength = str1.length
|
|
// get second string length.
|
|
const secondStringLength = str2.length
|
|
// absolute length for operation.
|
|
const absLength =
|
|
firstStringLength > secondStringLength
|
|
? firstStringLength
|
|
: secondStringLength
|
|
|
|
// Iterate the character count until the absolute count is reached.
|
|
for (let charCount = 0; charCount < absLength; charCount++) {
|
|
// If firstStringLength is lesser than the charCount it means they are able to re-arrange.
|
|
if (charCount < firstStringLength) {
|
|
outStr += str1[charCount]
|
|
}
|
|
|
|
// If secondStringLength is lesser than the charCount it means they are able to re-arrange.
|
|
if (charCount < secondStringLength) {
|
|
outStr += str2[charCount]
|
|
}
|
|
}
|
|
|
|
// return the output string.
|
|
return outStr
|
|
}
|
|
|
|
export { AlternativeStringArrange }
|