Skip to content

Commit e0b60d4

Browse files
authored
Create array-nesting.py
1 parent 32e56da commit e0b60d4

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Python/array-nesting.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# A zero-indexed array A consisting of N different integers is given.
5+
# The array contains all integers in the range [0, N - 1].
6+
#
7+
# Sets S[K] for 0 <= K < N are defined as follows:
8+
#
9+
# S[K] = { A[K], A[A[K]], A[A[A[K]]], ... }.
10+
#
11+
# Sets S[K] are finite for each K and should NOT contain duplicates.
12+
#
13+
# Write a function that given an array A consisting of N integers,
14+
# return the size of the largest set S[K] for this array.
15+
#
16+
# Example 1:
17+
# Input: A = [5,4,0,3,1,6,2]
18+
# Output: 4
19+
# Explanation:
20+
# A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
21+
#
22+
# One of the longest S[K]:
23+
# S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
24+
# Note:
25+
# N is an integer within the range [1, 20,000].
26+
# The elements of A are all distinct.
27+
# Each element of array A is an integer within the range [0, N-1].
28+
29+
class Solution(object):
30+
def arrayNesting(self, nums):
31+
"""
32+
:type nums: List[int]
33+
:rtype: int
34+
"""
35+
result = 0
36+
for num in nums:
37+
if num != None:
38+
start, count = num, 0
39+
while nums[start] != None:
40+
temp = start
41+
start = nums[start]
42+
nums[temp] = None
43+
count += 1
44+
result = max(result, count)
45+
return result
46+

0 commit comments

Comments
 (0)