Day 1: Force buckle 344, reverse string:
Write a function that reverses the input string. The input string is given in the form of the character array char[]. Instead of allocating extra space to another array, you must modify the input array in place, using O(1) extra space to solve the problem. You can assume that all the characters in the array are printable characters in the ASCII code table.
My chicken size:
var reverseString = function(s) {
for (let i =s.length-1; i>=0; i–)
{
s.push(s[i]);
s.splice(i,1);
}
return s;
};
Execution time: 340 ms, beating 5.08% of all JavaScript commits
Memory consumption: 46.5 MB, beating 5.04% of all JavaScript commits
Then we introduced a method called Reverse, which directly reverses array elements:
var reverseString = function(s) {
s.reverse();
return s;
};
Execution time: 124 ms, beating 58.83% of users in all JavaScript commits
Memory consumption: 44.4 MB, beating 19.76% of all JavaScript commits
Then I came across a method that was also good:
var reverseString = function(s) {
let x=s.length-1;
let y=0;
while(x>y)
{
[s[x],s[y]]=[s[y],s[x]];
x–;
y++;
}
return s;
};