-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpartition.js
More file actions
44 lines (41 loc) · 1.05 KB
/
Copy pathpartition.js
File metadata and controls
44 lines (41 loc) · 1.05 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
"use strict";
/**
* Travel through list and maintain two lists as we travel through. One list
* contains all the items less than the partition value and the other contains
* all the items greater than or equal to it.
*
* N = |list|
* Time: O(N)
* Additional space: O(1) -> as new structures aren't being created, original
* list is being manipulated.
*/
export function partition(list, val) {
let node = list,
smallerHead,
smallerTail,
largerHead,
largerTail;
smallerHead = smallerTail = largerHead = largerTail = null;
while (node) {
let next = node.next;
node.next = null;
if (node.val >= val) {
if (!largerTail) {
largerHead = largerTail = node;
} else {
largerTail = largerTail.next = node;
}
} else if (node.val < val) {
if (!smallerHead) {
smallerHead = smallerTail = node;
} else {
smallerTail = smallerTail.next = node;
}
}
node = next;
}
if (smallerTail) {
smallerTail.next = largerHead;
}
return smallerHead || largerHead;
}