Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find and return the longest length of set in JavaScript
In JavaScript, finding the longest length of a set involves traversing array elements in a cycle pattern where each element points to the next index. This problem requires tracking visited elements to avoid infinite loops and find the maximum cycle length.
Problem Statement
Given an array of length N containing all integers from 0 to N-1, we need to find the longest set S where S[i] = {A[i], A[A[i]], A[A[A[i]]], ...}. We start from index i, then move to A[i], then to A[A[i]], and continue until we encounter a duplicate element.
Example Input and Output
For the array:
const arr = [5, 4, 0, 3, 1, 6, 2];
The expected output is 4, representing the longest cycle length.
Output Explanation
Array mapping: A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
One of the longest sets:
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
Solution Using Recursive Approach
const arr = [5, 4, 0, 3, 1, 6, 2];
const arrayNesting = (arr = []) => {
const visited = {};
const aux = (index) => {
if (visited[index]) {
return 0;
}
visited[index] = true;
return aux(arr[index]) + 1;
};
let max = 0;
arr.forEach((n, index) => {
if (!visited[index]) {
max = Math.max(max, aux(index));
}
});
return max;
};
console.log(arrayNesting(arr));
4
Alternative Iterative Solution
const arrayNestingIterative = (arr = []) => {
const visited = new Array(arr.length).fill(false);
let maxLength = 0;
for (let i = 0; i
4
How It Works
The algorithm uses a visited array to track processed elements. For each unvisited starting index, it follows the chain of indices until reaching a previously visited element. The length of each chain is calculated, and the maximum length across all chains is returned.
Key Points
- Each element can only be part of one cycle due to the array's properties
- Once an element is visited, it doesn't need to be processed again
- Time complexity: O(n), Space complexity: O(n)
Conclusion
Finding the longest set length requires cycle detection in arrays. Both recursive and iterative approaches work effectively, with the iterative solution being more memory-efficient for large datasets.
