Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
ProgrammingMiddleOccasionalPractical

How would you detect a cycle in a linked list and test the solution?

Answer

Use a slow pointer that advances one node and a fast pointer that advances two. They meet if a cycle exists; reaching the end proves the list is acyclic. This uses linear time and constant extra space. Test an empty list, one node with and without a self-cycle, a cycle beginning at the head or middle, and a long acyclic list.

Strong answer includes

  • explains the slow and fast pointer invariant
  • states linear time and constant auxiliary space
  • covers self-cycles and cycles at different positions

Practical example

A candidate's first implementation compares node values instead of node references to detect a repeat, which incorrectly flags a cycle in an acyclic list that happens to contain two nodes holding the same value; switching the comparison to pointer identity fixes it.

#linked-list#cycle-detection#sdet#coding-interview

Sources

MIT OpenCourseWare — Introduction to AlgorithmsMIT OpenCourseWare · Data structures, algorithmic reasoning and time and space complexitySoftware Testing Interview Questions and AnswersGeeksforGeeks · Prevalence signal across manual, automation and technical testing topics