R
E
A
C
T
O
xamples
epeat
ode
pproach
ptimize
est
Cyclic Linked List
Problem
Given the head of a singly linked list, determine if there is a cycle. If there is, return the length of the cycle, and the first node in the cycle.
Easy, right?
Here's the catch:
- You cannot use any additional data structures. No arrays, no objects, no maps, no linked lists, you get the point.
Any ideas?
What would the linked list above return?
Answer
Length: 6
Start Node: 3
The Runner Technique
- Instantiate one variable (slowNode) to point to the startNode
- Instantiate another variable (fastNode) to point to the next node.
- Advance the slowNode one node at a time.
- Advance the fastNode two nodes at a time.
- At each iteration, check if their values are equal.
- If they're equal, you have found a cycle.
Finding the cycle solution
Determining Cycle Length
- You have two nodes, both point to the same node in the cycle.
- Keep the fastNode stationary
- Increment the slowNode by one node, incrementing a counter at each iteration.
- Break the while loop once the two nodes are equal again.
- Return the counter -> that's your cycle length.
Determining Cycle Length
Finding the start of the cycle
- You know P, the length of the cycle.
- You will use the runner technique for this step as well.
- Instantiate two variables that point to the startNode.
- Advance the fastNode P nodes into the linked list.
- Then, advance the fastNode and the slowNode one node at a time.
- Check if they are equal at each iteration.
- Return the node when they are equal.
Finding the start node
REPL of Solution - https://repl.it/BlUo/
Conclusion
Solution : https://repl.it/BlUo/
Key Takeaways:
- Be very comfortable with Linked Lists
- Understand how to find cycles in data structures.
Cyclic Linked List
By ryankdwyer
Cyclic Linked List
Technical interview problem on generating string permutations
- 1,023