Sponsored
Sponsored
In this approach, we use an auxiliary 'visited' array to keep track of the elements that have already been included in any set s[k]
. For each unvisited element at index i
, we keep iterating through the sequence by accessing nums[nums[i]]
until we encounter an element already visited. Each time we reach an unvisited element, we mark it as visited, and increment the length of the current sequence. We keep track of the longest length among all sequences generated from each starting index.
Time Complexity: O(N), where N is the number of elements in the array, as each element is visited at most once.
Space Complexity: O(N) due to the additional 'visited' array.
1using System;
2
3public class Solution {
4 public int ArrayNesting(int[] nums) {
5 bool[] visited = new bool[nums.Length];
6 int max_length = 0;
7 for (int i = 0; i < nums.Length; i++) {
8 if (!visited[i]) {
9 int start = i, length = 0;
10 do {
11 visited[start] = true;
12 start = nums[start];
13 length++;
14 } while (!visited[start]);
15 max_length = Math.Max(max_length, length);
16 }
17 }
18 return max_length;
19 }
20
21 public static void Main() {
22 Solution solution = new Solution();
23 int[] nums = {5, 4, 0, 3, 1, 6, 2};
24 Console.WriteLine(solution.ArrayNesting(nums));
25 }
26}
This C# implementation leverages a boolean array to identify elements which have already been included in sequences. The solution contains loops that continuously concatenate indices until repetition occurs, updating the longest nested length as necessary through Math.Max()
.
This approach minimizes space usage by modifying the input array itself as a marker of visited nodes. By setting each visited position to a sentinel value (e.g., -1 or a number outside the expected range), we can achieve the same iterative closure tracking. We simply iterate over each number and trace the sequence until we circle back to a marked node. This is an improvement on memory constraints when needing to handle particularly large datasets.
Time Complexity: O(N), executing a linear pass through the nodes.
Space Complexity: O(1), modifying input without auxiliary space.
Java demonstrates similar in-place ordering by marking elements inside the main integer array, checking segment frequency with temporary values. These help confirm chain end points, stopping once finished loops are attained, which achieves reliable performance free from additional data costs.