Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to count number of elements present in a set of elements with recursive indexing in Python
Recursive indexing involves creating a chain of elements by repeatedly using values as indices. Given a list A and starting index k, we build a set {A[k], A[A[k]], A[A[A[k]]], ...} until we reach an out-of-bounds index or detect a cycle.
If there's a cycle (we encounter the same value twice), we return -1. Otherwise, we return the size of the unique elements collected.
Example Walkthrough
For A = [1,2,3,4,5,6,7] and k = 1:
- A[1] = 2, add 2 to set
- A[2] = 3, add 3 to set
- A[3] = 4, add 4 to set
- A[4] = 5, add 5 to set
- A[5] = 6, add 6 to set
- A[6] = 7, add 7 to set
- A[7] is out of bounds, so stop
The set {2,3,4,5,6,7} has size 6.
Algorithm
To solve this, we follow these steps ?
- Initialize an empty set to track seen values
- While k is within bounds of A:
- If A[k] is already seen, return -1 (cycle detected)
- Add A[k] to the seen set
- Update k to A[k] for next iteration
- Return the size of the seen set
Implementation
def count_recursive_indexing(A, k):
seen = set()
while k < len(A):
if A[k] in seen:
return -1 # Cycle detected
seen.add(A[k])
k = A[k]
return len(seen)
# Test with the given example
A = [1, 2, 3, 4, 5, 6, 7]
k = 1
result = count_recursive_indexing(A, k)
print(f"Size of set: {result}")
# Test with cycle detection
A_cycle = [1, 2, 1, 4] # A[1]=2, A[2]=1 creates cycle
k_cycle = 1
result_cycle = count_recursive_indexing(A_cycle, k_cycle)
print(f"Cycle test result: {result_cycle}")
Size of set: 6 Cycle test result: -1
How It Works
The algorithm uses a set to track visited values and detect cycles. Each iteration adds the current element A[k] to the set, then moves to index A[k]. If we encounter a value we've seen before, it indicates a cycle, so we return -1.
Edge Cases
# Empty traversal (k out of bounds) print(count_recursive_indexing([1, 2, 3], 5)) # Returns 0 # Single element print(count_recursive_indexing([0], 0)) # Returns 1 # Immediate cycle print(count_recursive_indexing([0, 1], 0)) # Returns -1
0 1 -1
Conclusion
This algorithm efficiently counts unique elements in a recursive indexing chain while detecting cycles. The time complexity is O(n) where n is the number of unique elements visited, and space complexity is O(n) for the seen set.
