Detect cycles in lists and graphs | Amazon Interview Question