One Pager Cheat Sheet
- Get your feet wet with hands-on experience of essential data structures and algorithms by completing the
reverseString
challenge as a way to power through the AlgoDaily technical interview course and set yourself up for success in landing your dream software engineering job. - Strings are
immutable
, sotransformation algorithms
are necessary to create anew string object
when performing operations like reversing a string, preserving the original string and its properties. - Reverse a string is one of the most common interview questions for software engineers, and though it seems simple, a brute force solution can be done by iterating from the back to the front using string indices.
- We can use a
for loop
toconsole.log
out each element of the arrayarr
from the end to the start, decrementing the index position by 1 each time the loop is iterated, beginning witharr.length - 1
. - We can optimize the string reversal brute force approach by using the Two Pointer Technique with a
while
loop and swapping letters at each iteration, reducing the number of operations required by half. - The
two pointers technique
can be used to reduce the complexity of a nested for-loop fromO(n^2)
toO(n)
, significantly improving the efficiency of a solution. - The time complexity of reversing a string using two pointers is still
O(n)
, as the number of swaps increases in proportion to the input size.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
60
}
var assert = require('assert');
​
function reverseString(str) {
let strArr = str.split('');
let start = 0;
let end = str.length - 1;
​
while (start <= end) {
const temp = strArr[start];
strArr[start] = strArr[end];
strArr[end] = temp;
start++;
end--;
}
​
return strArr.join('');
}
​
try {
assert.equal(
reverseString('njnschnjkdasn j32 uida'),
'adiu 23j nsadkjnhcsnjn'
);
​
console.log(
'PASSED: ' +
"`reverseString('njnschnjkdasn j32 uida')` should return `'adiu 23j nsadkjnhcsnjn'`"
);
} catch (err) {
console.log(err);
}
​
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
You're doing a wonderful job. Keep going!
If you had any problems with this tutorial, check out the main forum thread here.