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.
This C program uses an iterative method with a boolean array to track visited elements. It loops through each element in the array and checks sequences starting from unvisited indices. The nested do-while loop continues until a visited element is encountered, at which point the sequence stops. The maximum length of the sequences encountered is stored and returned.
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.
1#include <stdio.h>
2
3int arrayNesting(int* nums, int numsSize){
4 int max_length = 0;
5 for (int i = 0; i < numsSize; i++) {
6 if (nums[i] != -1) {
7 int start = i, length = 0;
8 while (nums[start] != -1) {
9 int temp = nums[start];
10 nums[start] = -1;
11 start = temp;
12 length++;
13 }
14 if (length > max_length) max_length = length;
15 }
16 }
17 return max_length;
18}
19
20int main() {
21 int nums[] = {5, 4, 0, 3, 1, 6, 2};
22 int numsSize = sizeof(nums)/sizeof(nums[0]);
23 printf("%d\n", arrayNesting(nums, numsSize));
24 return 0;
25}
The C program adopts in-place marking to track progressing paths within nesting procedures. The primary loop controls the sequence length, adjusting and modifying indices by placing distinctions (as sentinel values) when indexes are processed. The solution ends by providing the largest found sequence, sidestepping additional space use for a tracker array.
Solve with full IDE support and test cases