> For the complete documentation index, see [llms.txt](https://maksimdan.gitbook.io/interview-practice-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://maksimdan.gitbook.io/interview-practice-problems/coding_practice_questions/interview_questions_7/circular-array.md).

# Circular Array

**7.9 Circular Array:** Implement a `CircularArray` class that supports an array-like data structure which can be efficiently rotated. If possible, the class should use a generic type (also called a template), and should support iteration via the standard for (Obj 0 : circularArray) notation.

**The Idea:** Override/redefine the iterater methods, and maintain a counter that mods off the array size.

**Complexity:** O(1) retrival methods

```python
class CircularArray:
    def __init__(self, ar, start):
        """
        :param ar: List[<type>] - iterable list
        :param start: [int] - start of iteration, zero indexed
        """
        self.ar = ar
        self.length = len(ar)
        self.iter = start
        self.remainder = len(ar)

    def __iter__(self):
        return self

    def __next__(self):
        """
        :return: next iterable it exists, otherwise
                 and exception gets raised
        """
        if self.remainder == 0:
            raise StopIteration
        else:
            self.iter += 1
            self.remainder -= 1
            return self.ar[(self.iter - 1) % self.length]


# interally the exceptions gets caught in the ranged loop
ca = CircularArray([1,2,3,4,5], 2)
for num in ca:
    print(num, end=' ')
```
