Skip to content

Instantly share code, notes, and snippets.

@kylejeske
Created July 21, 2019 20:24
Show Gist options
  • Save kylejeske/aa964f54821ed4c6d2086b99adb36372 to your computer and use it in GitHub Desktop.
Save kylejeske/aa964f54821ed4c6d2086b99adb36372 to your computer and use it in GitHub Desktop.
Flipping bits - RunTime: o(n), Space: o(n)
// Start with: ['a', 'b', 'c', 'd', 'e']
// End with: ['a', 'b', 'c', 'd', 'e']
// without using any additional variables, and within o(n) runtime.
// swapArr (reference Array, pointer 1, pointer 2)
// will take the reference to the position within the array
// and swap them without using a third variable
const swapArr = (arr, x,y) => {
// replace ASCII values with the character decimals
arr[x] = arr[x].charCodeAt(0);
arr[y] = arr[y].charCodeAt(0);
// do a XOR bitwise comparison & swap
arr[x] = arr[x]^arr[y];
arr[y] = arr[x]^arr[y];
arr[x] = arr[x]^arr[y];
// switch the characters back to the ASCII values
arr[x] = String.fromCharCode(arr[x]);
arr[y] = String.fromCharCode(arr[y]);
return arr;
}
const main = () => {
let _arr = ['a','b','c','d','e'];
console.log(`Before: ${_arr}`);
// start pointers at beginning and end of array
// then loop until we meet in the middle
let n = _arr.length;
let s = 0;
let e = n - 1;
while (s < e) {
// swap the letters
_arr = swapArr(_arr, s, e);
s++;
e--;
}
console.log(`After: ${_arr}`);
}
// runner function
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment