You are given an array of characters arr that consists of sequences of characters separated by space characters. Each space-delimited sequence of characters defines a word.
Implement a function reverseWords that reverses the order of the words in the array in the most efficient manner.
Explain your solution and analyze its time and space complexities.
input: arr = [ 'p', 'e', 'r', 'f', 'e', 'c', 't', ' ',
'm', 'a', 'k', 'e', 's', ' ',
'p', 'r', 'a', 'c', 't', 'i', 'c', 'e' ]
output: [ 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ',
'm', 'a', 'k', 'e', 's', ' ',
'p', 'e', 'r', 'f', 'e', 'c', 't' ]
function reverseWords(arr) {
const str = arr.join('').replace(',',''); //Convert arry to string to split
const input = str.split(' '); // Split into words
const ans = input.reduceRight((a,b)=> a.concat((b+" ").split('')), []); //revers words add space back
return ans.slice(0,-1); //trim last space.
}function reverseWords(arr) {
const input = arr.join('').replace(',','').split(' '); //Split array into words
return input.reduceRight((a,b)=> [...a, ...b, " "],[]).slice(0,-1); // Reverse words trimming last space
}