-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlce_p2677_chunk_array.js
More file actions
63 lines (48 loc) · 1.17 KB
/
lce_p2677_chunk_array.js
File metadata and controls
63 lines (48 loc) · 1.17 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
LCE 2677. Chunk Array
Given an array arr and a chunk size size, return a chunked array.
A chunked array contains the original elements in arr, but consists of subarrays each of length size.
The length of the last subarray may be less than size if arr.length is not evenly divisible by size.
You may assume the array is the output of JSON.parse.
In other words, it is valid JSON.
Please solve it without using lodash's _.chunk function.
Constraints:
- arr is a valid JSON array
- 2 <= JSON.stringify(arr).length <= 10^5
- 1 <= size <= arr.length + 1
*/
/**
* @param {Array} arr
* @param {number} size
* @return {Array}
*/
// plain push
// Time: O(n)
// Space: O(n)
var chunk = function (arr, size) {
let chunks = [];
let temp = [];
for (const num of arr) {
temp.push(num);
if (temp.length === size) {
chunks.push(temp);
temp = [];
}
}
if (temp.length) {
chunks.push(temp);
}
return chunks;
};
// using slicing (recommended)
// Time: O(n)
// Space: O(1)
var chunk = function (arr, size) {
let chunks = [];
let ptr = 0;
while (ptr < arr.length) {
chunks.push(arr.slice(ptr, ptr + size));
ptr += size;
}
return chunks;
};