Detect cycles in lists and graphs
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of cycle detection in linked lists and directed graphs, assessing competencies in pointer manipulation, graph traversal strategies, and reasoning about algorithmic time and space complexity within the Coding & Algorithms domain.
Detect Cycle In A Linked List
Constraints
- Inputs are Python literals matching the function signature.
- Return a deterministic exact-match value.
Examples
Input: ([1,2,3,1], 0)
Expected Output: True
Explanation: The list cycles back to index 1.
Input: ([1,2,-1], 0)
Expected Output: False
Explanation: The list terminates.
Input: ([0], 0)
Expected Output: True
Explanation: A node that points to itself is a cycle.
Hints
- Use Floyd slow and fast pointers.
- Treat -1 as the end of the list.
Detect Reachable Cycle In A Directed Graph
Constraints
- Inputs are Python literals matching the function signature.
- Return a deterministic exact-match value.
Examples
Input: {0:[1],1:[2],2:[0]}, 0
Expected Output: True
Explanation: A directed cycle is reachable from start.
Input: ({"a":["b","c"],"b":[],"c":[]}, "a")
Expected Output: False
Explanation: A DAG has no cycle.
Input: ([[1],[2],[]], 0)
Expected Output: False
Explanation: List adjacency is supported.
Hints
- Use DFS colors: visiting means on the recursion stack.
- Only nodes reachable from start need to be explored.