Skip to content

Instantly share code, notes, and snippets.

@ironars
Created January 1, 2020 14:09
Show Gist options
  • Select an option

  • Save ironars/d70496ae6f7d2fa2f81dd4e34edf2704 to your computer and use it in GitHub Desktop.

Select an option

Save ironars/d70496ae6f7d2fa2f81dd4e34edf2704 to your computer and use it in GitHub Desktop.
How to reverse words in a character array
// Input: [
// "J",
// "o",
// "i",
// "n",
// " ",
// "U",
// "s",
// " ",
// "N",
// "o",
// "w"
// ]
var data = "Join Us Now".split(""); // creates the input array.
function reverseLettersOnly(arr) {
if (!arr.length) return arr;
let start = 0;
let end = arr.length;
let spaceIndex = -1;
for (let index = 0; index < arr.length; index++) {
if (arr[index] === " ") {
spaceIndex = index;
end = spaceIndex;
}
if (spaceIndex >= 0) {
console.log("spaceIndex: ", spaceIndex);
// end = index - 1;
console.log("old arr:", arr);
const subArr = arr.slice(start, end).reverse();
console.log("subArr: ", subArr);
arr.splice(start, end - start, ...subArr);
console.log("new arr: ", arr);
start = spaceIndex + 1;
end = arr.length - 1;
spaceIndex = -1;
console.log("start: ", start);
console.log("end: ", end);
} else if (index === arr.length - 1) {
// single word
console.log("start: ", start);
console.log("end: ", end);
const subArr = arr.slice(start).reverse();
arr.splice(start, end, ...subArr);
}
}
}
reverseLettersOnly(data);
console.log("result: ", data);
@ironars
Copy link
Author

ironars commented Jan 2, 2020

spaceIndex is required to set the next value for start.

@nomanalikhan
Copy link

spaceIndex is required to set the next value for start.

see this!
https://github.com/nomanalikhan/hacker-rank-solutions/blob/master/reverse-letters-only/solution.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment