-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseArray.js
More file actions
32 lines (29 loc) · 761 Bytes
/
reverseArray.js
File metadata and controls
32 lines (29 loc) · 761 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Write a function that reverses an array.
// Do not allocate extra space for another array,
// you must do this by modifying the input array in-place with O(1) extra memory.
// You may assume all the characters consist of printable ascii characters.
//
// Recursive Solution
/**
* @param {character[]} s
* @return {void} Do not return anything, modify s in-place instead.
*/
function reverseArray(arr) {
if (arr.length <= 1)
return arr
let element = arr.shift();
reverseArray(arr)
arr.push(element)
return arr
};
/*
* More efficient approach
*/
const reverseArray = arr => {
for (let i = 0; i < arr.length / 2; i++) {
let temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
return arr;
};