
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Count Number of Elements in a Set 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
Advertisements