With two pointers, we've cut the number of operations in half. It's much faster now! However, similar to the brute force, the time complexity is still O(n)
.

Why Is This?
Well, if n
is the length of the string, we'll end up making n/2
swaps. But remember, Big O Notation
isn't about the raw number of operations required for an algorithm-- it's about how the number scales with the input.
So despite requiring half the number operations-- a 4
-character string would require 2
swaps with the two-pointer method. But an 8
-character string would require 4
swaps. The input doubled, and so did the number of operations.
If you haven't by now, try to do the problem before moving on.
xxxxxxxxxx
50
var assert = require('assert');
function reverseString(str) {
// reverse str
return str;
}
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);
}
try {
assert.equal(reverseString('timbuktu12'), '21utkubmit');
console.log(
'PASSED: ' + "`reverseString('timbuktu12')` should return `'21utkubmit'`"
);
OUTPUT
Results will appear here.