Skip to content

565. Array Nesting

Difficulty: Medium

LeetCode Problem View on GitHub


565. Array Nesting

Medium


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[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:

  • The first element in s[k] starts with the selection of the element nums[k] of index = k.
  • The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.
  • We stop adding right before a duplicate element occurs in s[k].

Return the longest length of a set s[k].

 

Example 1:

Input: nums = [5,4,0,3,1,6,2]
Output: 4
Explanation: 
nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
One of the longest sets s[k]:
s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}

Example 2:

Input: nums = [0,1,2]
Output: 1

 

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] < nums.length
  • All the values of nums are unique.

Solution

class Solution {
    private ArrayList<ArrayList<Integer>> adj;
    private int dp[];
    public int arrayNesting(int[] nums) {
        int n = nums.length;
        adj = new ArrayList<>();
        dp = new int[n + 1];
        for (int i = 0; i <= n + 1; i++) adj.add(new ArrayList<>());
        for (int i = 0; i < n; i++) {
            if (i == nums[i]) continue;
            adj.get(i).add(nums[i]);
        }
        int maxi = 0;
        int vis[] = new int[n + 1];
        for (int i = 0; i < n; i++) {
            if (vis[i] == 0) dfs(i, -1, vis);
        }
        for (int i = 0; i < n; i++) maxi = Math.max(maxi, dp[i]);
        return maxi + 1;
    }
    private void dfs(int u, int par, int vis[]) {
        vis[u] = 1;
        for (int v : adj.get(u)) {
            if (vis[v] == 0) {
                dfs(v, u, vis);
                dp[u] = Math.max(dp[u], 1 + dp[v]);
            }
        }
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Approach

Detailed explanation of the approach will be added here