Created
May 29, 2017 16:55
-
-
Save rebeccapeltz/4874ad7108fcc1d6163bc38c23d87c10 to your computer and use it in GitHub Desktop.
Reverse a string O(N) and O(N/2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// O(N) | |
function(str) { | |
if (str.length < 2) return str; | |
return str.split('').reverse().join(''); | |
} | |
// O(N/2) | |
function(str) { | |
var buffer = new Buffer(str); | |
for (var i=0;i< buffer.length/2; i++){ | |
var swap = buffer[i]; | |
buffer[i] = buffer[buffer.length - 1 - i]; | |
buffer[buffer.length - 1 - i] = swap; | |
} | |
return buffer.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment