Array Nesting

MediumArrays & Hashingsimulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an array nums of length n that is a permutation of 0 .. n - 1. Starting from any index k, build the sequence nums[k], nums[nums[k]], nums[nums[nums[k]]], ... and stop just before a value would repeat. Return the length of the longest such sequence over all starting indices. Aim for O(n) time.

Examples

Input: nums = [5,4,0,3,1,6,2]
Output: 4
Starting at index 0 gives 5, 6, 2, 0, then 5 would repeat.
Input: nums = [0,1,2]
Output: 1
Every index points to itself.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] < nums.length
  • All values of `nums` are distinct

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More simulation problems