-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patharray-partitioning.js
72 lines (59 loc) · 1.27 KB
/
array-partitioning.js
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
64
65
66
67
68
69
70
71
/*
*
* --------------------
* | ARRAY PARTITIONING |
* --------------------
*
*
* Given k and an array of numbers. Return
* "Yes" if it is possible to partition the
* array into subpartitions that are of size = k.
* Each partition must contain only distict numbers.
*
* e.g.
*
* numArr = [1, 3, 4 ]
*
* partitionArray(numArr) // returns 1 + 3 + 4
*
*
* */
/*
*
* ***** SOLUTION
*
* */
function partitionArray(k, numsArr) {
// init numsMap
const numsMap = {};
// populate numsMap wirh for loop
for(let num of numsArr) {
numsMap[num] = numsMap[num] + 1 || 1
};
if( (numsArr.length % k) !== 0){
return "No";
};
console.log("numsMap -- ", numsMap);
// loop over numsMap
for(let num in numsMap) {
// if a value > k
if(numsMap[num] > k) {
// return "No"
return "No";
};
};
// return "Yes"
return "Yes";
};
/*
*
* ***** TESTS
*
* */
const k = 2;
const numsArr1 = [4,4,3,4];
console.log("## TEST 1 ----- > ", partitionArray(k, numsArr1)); // "Yes"
// const k, numsArr2 = null;
// console.log("## TEST 2 ----- > ", partitionArray(k, numsArr2)); // 100
// const k, numsArr3 = null;
// console.log("## TEST 3 ----- > ", partitionArray(k, numsArr3)); // 128