10 Patterns to Master Linked List for Interviews:
10 Patterns to Master Linked List for Interviews:
1. Dummy Head
Add a sentinel node before the head. Deleting the first node no longer needs a special case.
2. Reverse a List
Three pointers (prev, curr, next), flip one arrow at a time. O(n) time, O(1) space.
3. Fast & Slow Pointers
Slow moves 1 step, fast moves 2. When fast hits the end, slow is at the middle.
4. Cycle Detection (Floyd's)
Same two pointers. If there's a loop, fast must eventually catch slow. If they collide, you have a cycle.
5. Remove Nth From End
Move a lead pointer n steps ahead, then advance both together. When lead ends, trail is right before the target. One pass.
6. Merge Two Sorted Lists
Always take the smaller of the two heads. Time O(n+m).
7. Palindrome Check
Find the middle (pattern 3), reverse the back half (pattern 2), compare inward.
8. Intersection of Two Lists
When a pointer hits the end, switch it to the other list's head. Both walk a+c+b = b+c+a steps and meet at the intersection.
9. Reverse in k-Groups
Reverse one block of k, recurse on the rest, stitch them together.
10. LRU Cache
Doubly linked list + hash map. The list keeps recency order, the map gives O(1) lookup. Every operation is O(1).
#dsa #coding #interviews #algorithms #algomaster
Comments
Comments from the original post on Instagram
No comments yet
