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:

  1. 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

  1. Instantiate one variable (slowNode) to point to the startNode
  2. Instantiate another variable (fastNode) to point to the next node.
  3. Advance the slowNode one node at a time. 
  4. Advance the fastNode two nodes at a time.
  5. At each iteration, check if their values are equal. 
    1. If they're equal, you have found a cycle.

Finding the cycle solution

Determining Cycle Length

  1. You have two nodes, both point to the same node in the cycle.
  2. Keep the fastNode stationary
  3. Increment the slowNode by one node, incrementing a counter at each iteration.
  4. Break the while loop once the two nodes are equal again. 
  5. Return the counter -> that's your cycle length.

Determining Cycle Length

Finding the start of the cycle

  1. You know P, the length of the cycle.
  2. You will use the runner technique for this step as well. 
  3. Instantiate two variables that point to the startNode.
  4. Advance the fastNode P nodes into the linked list.
  5. Then, advance the fastNode and the slowNode one node at a time.
  6. Check if they are equal at each iteration.
  7. 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:

  1. Be very comfortable with Linked Lists
  2. 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