-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0932-beautiful-array.js
More file actions
34 lines (28 loc) · 882 Bytes
/
0932-beautiful-array.js
File metadata and controls
34 lines (28 loc) · 882 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
33
34
/**
* Beautiful Array
* Time Complexity: O(N^2)
* Space Complexity: O(N^2)
*/
var beautifulArray = function (n) {
const resultCache = new Map();
function recursiveSolver(currentSize) {
if (resultCache.has(currentSize)) {
return resultCache.get(currentSize);
}
if (currentSize === 1) {
return [1];
}
const oddElementsSource = recursiveSolver(Math.ceil(currentSize / 2));
const evenElementsSource = recursiveSolver(Math.floor(currentSize / 2));
const transformedOdds = oddElementsSource.map(
(elementValueOne) => elementValueOne * 2 - 1,
);
const transformedEvens = evenElementsSource.map(
(elementValueTwo) => elementValueTwo * 2,
);
const finalArray = [...transformedOdds, ...transformedEvens];
resultCache.set(currentSize, finalArray);
return finalArray;
}
return recursiveSolver(n);
};