- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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]

- if A[k] in seen, then
- return size of seen

Let us see the following implementation to get better understanding −

## Example

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

- Related Questions & Answers
- Program to count number of sublists with exactly k unique elements in Python
- Python program to count number of substring present in string
- Program to count number of elements in a list that contains odd number of digits in Python
- Count number of elements in an array with MongoDB?
- Program to count number of elements are placed at correct position in Python
- Total number of elements present in an array in C#
- Count number of elements between two given elements in array in C++
- Count the number of elements in a HashSet in Java
- Count the number of masked elements in Numpy
- Count of matrices (of different orders) with given number of elements in C++
- Count Elements x and x+1 Present in List in Python
- Count occurrences of the average of array elements with a given number in C++
- Count of elements of an array present in every row of NxM matrix in C++
- Maximum number of contiguous array elements with same number of set bits in C++
- Count subarrays with equal number of occurrences of two given elements in C++

Advertisements