Improve robustness of graph cycle detection code | Uber Interview Question