[Python][Coding Pattern] Cycle Detection

 Cycle Detection

Purpose

The function checks whether a cycle exists in a dictionary-based chain of references.
A cycle occurs if a value eventually references a previously seen key in the chain.


Step-by-Step Logic

  1. Initialize a set to track visited keys
    We use a set to keep track of all keys we’ve already seen. This allows quick detection if we revisit a key.

  2. Start with a given starting key
    The traversal begins at the key provided as start. We treat this as the first node in the chain.

  3. Enter a while loop to follow the chain
    We use a while loop instead of a for loop because we don’t know how many steps it will take—the chain length is dynamic.

  4. Check if the current key is already visited

    • Inside the loop, if the current key is already in the visited set, it means we’ve come full circle → return True immediately (cycle detected).

  5. Otherwise, mark the current key as visited

    • Add the current key into the set so we can recognize it if it shows up again in the chain.

  6. Move to the next node in the chain

    • Reassign the variable holding the current key to the value that corresponds to the current key in the dictionary.

    • This value becomes the key to check in the next iteration.

  7. Repeat until there’s no next node

    • If we reach a point where the current key doesn’t appear in the dictionary, it means the chain ends → return False (no cycle detected).


Key Python Features Used

  • Set for uniqueness tracking: to efficiently check for previously visited keys.

  • While loop: for dynamic traversal through an unknown-length chain.

  • Dictionary lookup: using current = chain[current] to step forward in the chain.

  • Conditional early return: returning True as soon as a duplicate key is found in the set.

# Problem:
# Given a dictionary representing a chain of references,
# detect whether there is a cycle starting from a given key.
#
# Example Input:
# chain = {
#     "A": "B",
#     "B": "C",
#     "C": "D",
#     "D": "B"   # ← This creates a cycle: B → C → D → B
# }
#
# Expected Output:
# True (because there's a cycle)

def has_cycle(chain: dict, start: str) -> bool:
    visited = set()
    current = start

    while current in chain:
        if current in visited:
            return True
        visited.add(current)
        current = chain[current]

    return False

# Example Test Cases
if __name__ == '__main__':
    chain1 = {"A": "B", "B": "C", "C": "D"}
    assert has_cycle(chain1, "A") == False

    chain2 = {"A": "B", "B": "C", "C": "D", "D": "B"}
    assert has_cycle(chain2, "A") == True

    chain3 = {"X": "Y", "Y": "Z", "Z": "W"}
    assert has_cycle(chain3, "X") == False

    chain4 = {"X": "Y", "Y": "Z", "Z": "X"}
    assert has_cycle(chain4, "X") == True

Comments