Leetcode Problem 565: Array Nesting.
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 traversing the array from a start index i such that the set S contains the values:
S = {nums[i], nums[nums[i]], nums[nums[nums[i]]], ... }
The set stops adding values if a value that is already in the set is encountered. The goal is to find the longest length of set S.
Example:
Input: nums = [5, 4, 0, 3, 1, 6, 2]
Output: 4
Explanation:
nums[0] = 5, nums[5] = 6, nums[6] = 2, nums[2] = 0
Thereby, `S` = {5, 6, 2, 0}
nums consists of integers in the range [0, n-1].n?
n is within the constraints for competitive programming (1 <= n <= 10^4).visited of size n initialized to false. This will help us track if we have already visited an index.nums. If an index has not been visited yet, start a new set and keep track of its size.
nums as given by the problem statement. Mark each index as visited.Here’s how you can implement this in C++:
#include <vector>
#include <algorithm>
class Solution {
public:
int arrayNesting(std::vector<int>& nums) {
int n = nums.size();
std::vector<bool> visited(n, false);
int maxLength = 0;
for (int i = 0; i < n; ++i) {
if (!visited[i]) {
int length = 0;
int current = i;
while (!visited[current]) {
visited[current] = true;
current = nums[current];
++length;
}
maxLength = std::max(maxLength, length);
}
}
return maxLength;
}
};
n for the visited array.This efficient solution ensures that we achieve the goal within optimal time, adhering to competitive programming constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?