Skip to the solution
MediumDSAAsked in 20246 min read

Detect a Circular Reference in Any Object or Array Graph

3.0k views

The problem

Problem, as an interviewer would state it: "Write a function isCyclic(obj) that detects circular references anywhere in an object or array graph."

Examples:

Code
const a = { name: "a" }; a.self = a;
isCyclic(a); // true
isCyclic({ x: { y: [1, 2] } }); // false

Clarifying questions expected:

  • Is the same object appearing twice (but not inside itself) a cycle?
  • Which structures must be traversed — plain objects and arrays only, or also Map/Set?
  • How deep can the structure be, and does recursion depth matter?

Code / implementation expected: Yes — real, direct proof of a self-reference, an indirect cycle, an array cycle, and the shared-reference case that must NOT be reported.

  • object
  • graph

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: cycles are detected, a shared reference is correctly not a cycle, and a naive single seen-set gives a false positive

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 61 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Query String Parser

Continue