forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0019-remove-nth-node-from-end-of-list.js
74 lines (57 loc) · 1.54 KB
/
0019-remove-nth-node-from-end-of-list.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
72
73
74
/**
* https://leetcode.com/problems/remove-nth-node-from-end-of-list/
* Time O(N) | Space O(N)
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
const sentinel = new ListNode();
sentinel.next = head;
const fast = moveFast(sentinel, n); /* Time O(N) */
const slow = moveSlow(sentinel, fast);/* Time O(N) */
slow.next = slow.next.next || null;
return sentinel.next;
};
const moveFast = (fast, n) => {
for (let i = 1; i <= (n + 1); i++) {/* Time O(N) */
fast = fast.next;
}
return fast;
}
const moveSlow = (slow, fast) => {
while (fast) { /* Time O(N) */
slow = slow.next;
fast = fast.next;
}
return slow;
}
/**
* https://leetcode.com/problems/remove-nth-node-from-end-of-list/
* Time O(N) | Space O(1)
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
const length = getNthFromEnd(head, n);/* Time O(N) */
const isHead = length < 0;
if (isHead) return head.next;
const curr = moveNode(head, length); /* Time O(N) */
curr.next = curr.next.next;
return head
};
const getNthFromEnd = (curr, n, length = 0) => {
while (curr) { /* Time O(N) */
curr = curr.next;
length++;
}
return (length - n) - 1;
}
const moveNode = (curr, length) => {
while (length) { /* Time O(N) */
curr = curr.next;
length--;
}
return curr;
}