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.
1#include <iostream>
2#include <vector>
3
4using namespace std;
5
6template <typename T> void print_vector(const vector<T>& vec) {
7 for (const auto& x : vec)
8 cout << x << ' ';
9 cout << endl;
10}
11
12int arrayNesting(vector<int>& nums) {
13 vector<bool> visited(nums.size(), false);
14 int max_length = 0;
15 for (int i = 0; i < nums.size(); ++i) {
16 if (!visited[i]) {
17 int start = i, length = 0;
18 do {
19 visited[start] = true;
20 start = nums[start];
21 ++length;
22 } while (!visited[start]);
23 max_length = max(max_length, length);
24 }
25 }
26 return max_length;
27}
28
29int main() {
30 vector<int> nums = {5, 4, 0, 3, 1, 6, 2};
31 cout << arrayNesting(nums) << endl;
32 return 0;
33}
This C++ solution employs a std::vector
to store boolean values indicating which elements have been visited during the procedure. The outer loop initiates sequence generation from each index, and the inner do-while
loop tracks and updates indices until an index is reached again. It efficiently keeps track of visited indices through the boolean vector. The longest found sequence length is returned at the end.
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.