Grokking the Coding Interview: Patterns for Coding Questions
0% completed
Introduction to Fast & Slow Pointers Pattern
You are given a linked list. Your task is to decide whether the list contains a cycle.
A linked list contains nodes. Each node has a value and a next reference to another node.
Normally, following next eventually reaches the end of the list. In a cycle, one node points back to an earlier node. Following next then continues forever.
A simple solution remembers every node that you visit:
- Create an empty hash set.
- Walk through the list.
- Add each node to the set.
- If a node is already in the set, the list has a cycle.
This solution takes O(N) time and O(N) extra space.
.....
.....
.....
Like the course? Get enrolled and start learning!
Reading Progress
0%