Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1].
You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:
s[k] starts with the selection of the element nums[k] of index = k.s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.s[k].Return the longest length of a set s[k].
Example 1:
Input: nums = [5,4,0,3,1,6,2]
Output: 4
Explanation:
nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
One of the longest sets s[k]:
s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}
Example 2:
Input: nums = [0,1,2] Output: 1
Constraints:
1 <= nums.length <= 1050 <= nums[i] < nums.lengthnums are unique.Problem summary: You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1]. You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: The first element in s[k] starts with the selection of the element nums[k] of index = k. The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on. We stop adding right before a duplicate element occurs in s[k]. Return the longest length of a set s[k].
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[5,4,0,3,1,6,2]
[0,1,2]
nested-list-weight-sum)flatten-nested-list-iterator)nested-list-weight-sum-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #565: Array Nesting
class Solution {
public int arrayNesting(int[] nums) {
int n = nums.length;
boolean[] vis = new boolean[n];
int res = 0;
for (int i = 0; i < n; i++) {
if (vis[i]) {
continue;
}
int cur = nums[i], m = 1;
vis[cur] = true;
while (nums[cur] != nums[i]) {
cur = nums[cur];
m++;
vis[cur] = true;
}
res = Math.max(res, m);
}
return res;
}
}
// Accepted solution for LeetCode #565: Array Nesting
func arrayNesting(nums []int) int {
n := len(nums)
vis := make([]bool, n)
ans := 0
for i := 0; i < n; i++ {
if vis[i] {
continue
}
cur, m := nums[i], 1
vis[cur] = true
for nums[cur] != nums[i] {
cur = nums[cur]
m++
vis[cur] = true
}
if m > ans {
ans = m
}
}
return ans
}
# Accepted solution for LeetCode #565: Array Nesting
class Solution:
def arrayNesting(self, nums: List[int]) -> int:
n = len(nums)
vis = [False] * n
res = 0
for i in range(n):
if vis[i]:
continue
cur, m = nums[i], 1
vis[cur] = True
while nums[cur] != nums[i]:
cur = nums[cur]
m += 1
vis[cur] = True
res = max(res, m)
return res
// Accepted solution for LeetCode #565: Array Nesting
struct Solution;
impl Solution {
fn array_nesting(nums: Vec<i32>) -> i32 {
let mut res = 0;
let n = nums.len();
let mut visited = vec![false; n];
for i in 0..n {
if visited[i] {
continue;
}
let mut j = i;
let mut length = 0;
while !visited[j] {
visited[j] = true;
j = nums[j] as usize;
length += 1;
}
res = res.max(length);
}
res
}
}
#[test]
fn test() {
let nums = vec![5, 4, 0, 3, 1, 6, 2];
let res = 4;
assert_eq!(Solution::array_nesting(nums), res);
}
// Accepted solution for LeetCode #565: Array Nesting
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #565: Array Nesting
// class Solution {
// public int arrayNesting(int[] nums) {
// int n = nums.length;
// boolean[] vis = new boolean[n];
// int res = 0;
// for (int i = 0; i < n; i++) {
// if (vis[i]) {
// continue;
// }
// int cur = nums[i], m = 1;
// vis[cur] = true;
// while (nums[cur] != nums[i]) {
// cur = nums[cur];
// m++;
// vis[cur] = true;
// }
// res = Math.max(res, m);
// }
// return res;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.