Day4-Linked List 02
24. Swap Nodes in Pairs
Node:
- Understand Space Complexity(O(1))
second
variable is assigned the reference to a exist node in the current linkedlist- When you declare a variable inside a loop (e.g.,
const second = ...;
), memory is allocated for that variable only for the duration of that iteration. - Once the iteration completes and the variable goes out of scope, the memory can be reclaimed, especially in languages with garbage collection like JavaScript.
- This means that at any given time, there is only one instance of the second variable occupying memory, regardless of how many iterations the loop runs.
- If the algorithm were recursive, each recursive call would add a new layer to the call stack, resulting in O(n) space complexity
Time Complexity && Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)
1 | var swapPairs = function (head) { |
19. Remove Nth Node From End of List
Node:
- fast and slow poitner
- be case for the edge case, like
head = [1], n = 1
orhead = [1,2], n = 1
- be case for the edge case, like
Time Complexity && Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)
1 | var removeNthFromEnd = function (head, n) { |
160. Intersection of Two Linked Lists
Node:
- same value doesn’t mean same not
Time Complexity && Space Complexity
- Time Complexity: O(n+m)
- Space Complexity: O(1)
1 | var getIntersectionNode = function (headA, headB) { |
142. Linked List Cycle II
Note:
- fast and slow pointer - fast: head.next.next; - slow: head.next - fastLength: x+y+z+y - slowLength: x+y -
2*slowLength = fastLength
=>2(x+y) = x+y+z+y
=>x = y
Time Complexity && Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)
1 | var detectCycle = function (head) { |
- Title: Day4-Linked List 02
- Author: Guoyi
- Created at : 2024-08-25 17:27:42
- Updated at : 2024-12-07 03:58:41
- Link: https://guoyiwang.github.io/Algorithm/Day4-LinkedList02/
- License: This work is licensed under CC BY-NC-SA 4.0.
Comments