Can anyone explain what's the mistake in the below code?
function reverseString(str) {
let reversedStr = "";
for (let i = 0; i < str.length; i ) {
reversedStr.unshift(str[i]);
return str;
}
}
console.log(
reverseString("hello")
)
CodePudding user response:
You need an array to do unshift and the return outside the loop
const reverseString = str => {
const rev = [];
for (let i = 0; i < str.length; i ) rev.unshift(str[i])
return rev.join("")
};
console.log(
reverseString("hello")
)
but here is a oneliner
const reverseString = str => str ? [...str].reverse().join("") : str;
console.log(
reverseString("hello")
)
CodePudding user response:
If you meant to do the string reverse without using a util function, you can do it like below. If the string length is n then the time complexity of the below code is O(n/2).
function reverseString(str) {
// get single characters into array
const arrOfChars = str.split("");
// get the half size of the array
const halfLengthOfArr = Math.floor(arrOfChars.length / 2);
// start index
let i = 0;
// swap chars until reach the middle of the array
// h e l l o
// ^ ^
// o e l l h
// ^ ^
// o l l e h
while (i < halfLengthOfArr) {
// swap coupterparts from start and end with same distance
const start = arrOfChars[i];
arrOfChars[i] = arrOfChars[arrOfChars.length - (i 1)];
arrOfChars[arrOfChars.length - (i 1)] = start;
i ;
}
// return the output array as a string
return arrOfChars.join("");
}
console.log(reverseString("hello"));
