Skip to content

Commit 9cfc109

Browse files
authored
chore: Merge pull request TheAlgorithms#657 from suryapratapsinghsuryavanshi/master
Added AlternativeStringArrange method in string category.
2 parents 4788e99 + ae74e6b commit 9cfc109

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

String/AlternativeStringArrange.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Alternative arrange the two given strings in one string in O(n) time complexity.
2+
3+
// Problem Source & Explanation: https://www.geeksforgeeks.org/alternatively-merge-two-strings-in-java/
4+
5+
/**
6+
* Alternative arrange the two given strings in one string in O(n) time complexity.
7+
* @param {String} str1 first input string
8+
* @param {String} str2 second input string
9+
* @returns `String` return one alternative arrange string.
10+
*/
11+
const AlternativeStringArrange = (str1, str2) => {
12+
// firstly, check that both inputs are strings.
13+
if (typeof str1 !== 'string' || typeof str2 !== 'string') {
14+
return 'Not string(s)'
15+
}
16+
17+
// output string vlaue.
18+
let outStr = ''
19+
20+
// get first string length.
21+
const firstStringLength = str1.length
22+
// get second string length.
23+
const secondStringLength = str2.length
24+
// absolute length for oparetion.
25+
const absLenght = firstStringLength > secondStringLength ? firstStringLength : secondStringLength
26+
27+
// Iterate the character count until the absolute count is reached.
28+
for (let charCount = 0; charCount < absLenght; charCount++) {
29+
// If firstStringLength is lesser than the charCount it means they are able to re-arange.
30+
if (charCount < firstStringLength) {
31+
outStr += str1[charCount]
32+
}
33+
34+
// If secondStringLength is lesser than the charCount it means they are able to re-arange.
35+
if (charCount < secondStringLength) {
36+
outStr += str2[charCount]
37+
}
38+
}
39+
40+
// return the output string.
41+
return outStr
42+
}
43+
44+
module.exports = AlternativeStringArrange

0 commit comments

Comments
 (0)