Program to count number of elements present in a set of elements with recursive indexing in Python


Suppose we have a list of numbers called A and another number k, we have to make a new set of possible elements {A[k], A[A[k]], A[A[A[k]]], ... } stopping before it's out of index. We have to find the size of this set, otherwise -1 when there is a cycle.

So, if the input is like A = [1,2,3,4,5,6,7], k = 1, then the output will be 6 as A[1] = 2, A[2] = 3, A[3] = 4, A[4] = 5, A[5] = 6, A[6] = 7, So the set is {2,3,4,5,6,7}, size of set is 6.

To solve this, we will follow these steps −

  • seen := a new set
  • while k < size of A, do
    • if A[k] in seen, then
      • return -1
    • insert A[k] into seen
    • k := A[k]
  • return size of seen

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, A, k):
      seen = set()
      while k < len(A):
         if A[k] in seen:
            return -1
         seen.add(A[k])
         k = A[k]
      return len(seen)
ob = Solution()
print(ob.solve([1,2,3,4,5,6,7], 1))

Input

[1,2,3,4,5,6,7], 1

Output

6

Updated on: 07-Oct-2020

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements