JS - Two-Pointer Linked List Techniques
Qns: Create a function that returns the nth last element of a singly linked list.
Approach 1: Creating an entire parallel list
Use an array to store a representation of the linked list.
- Use up lots of memory maintaining a dual representation of the same data
- An approach like this results in an extra O(n) space being allocated.
Approach 2: Two-pointers
- O(n) time (we must iterate through the entire list once).
- O(1) space complexity (we always use only three variables no matter what size the list is).
Qns: Find the middle node of a linked list.
Approach: Two-pointers at Different Speeds
- Return the right-weighted middle for even-length lists.
- For example, in a list of 4 elements, return the element at index 2 (which would be the element 3).
Half-Speed
- Another equally valid solution is to move the fast pointer once with each loop iteration,
- but only move the slow pointer every-other iteration.