</> MAANG.io
coding interview Β· 101

Foundations

Master coding interviews with comprehensive coverage of data structures, algorithms, and problem-solving techniques. Progress from fundamentals to advanced topics with expertly curated content.

0/255 solved 0% complete

Circular Array Operations

What is this?

Imagine a clock face: after 12 comes 1 again β€” the numbers loop back instead of running off the edge. A circular array works the same way: the last slot connects back to the first, so you can keep stepping forward forever and you'll just go round and round. This is exactly how a running track, a carousel, or "whose turn is next" in a board game behaves, and it shows up constantly in real software like the buffers that smooth out streaming audio.

flowchart TD A["Two points on a ring"] --> B["Measure one arc"] B --> C["Other arc equals total minus that arc"] C --> D["Answer is the smaller of the two"]

πŸ’‘ Fun fact: The "wrap around with a remainder" trick (modular arithmetic) was formalized by Carl Friedrich Gauss in 1801, more than a century before computers existed. The very same idea now powers the consistent-hashing rings that let services like Cassandra and DynamoDB spread data across thousands of machines.

πŸ”“ The problem in this chapter is free. Sign in with Google or Microsoft to start solving.


The one-line idea: a circular array is just an ordinary array whose ends are glued together. Learn two reflexes β€” index with % n, and always consider "the other way around" β€” and a whole family of problems collapses into easy ones.


1. What "circular" really means

In a normal array, index 0 is the start and n‑1 is the end β€” fall off either edge and you're out of bounds. In a circular array, the element after n‑1 is 0 again. Bend the line into a ring:

Linear vs circular array: after index 4 wraps back to 0

Two tiny tools handle 95% of the wrap-around:

Move Formula Note
step forward (i + 1) % n clean
step backward (i - 1 + n) % n add n first so it never goes negative
jump k forward (i + k) % n

⚠️ In many languages -1 % n is negative (-1, not n‑1). Always normalise with (i - 1 + n) % n. (Python's % is non-negative, but write it the safe way out of habit β€” interviews are polyglot.)


2. Where you'll actually meet this

Circular arrays aren't a toy β€” they're how real systems reuse fixed memory and bounded structure:

  • Ring buffers / circular queues. Audio & network I/O buffers, Linux kernel ring buffers, Kafka-style append-with-wrap logs, lock-free SPSC queues β€” a fixed array with head/tail indices that wrap with % n.
  • Consistent-hashing rings (Cassandra, DynamoDB). Nodes and keys sit on a ring; ownership and replica walks go around it, often choosing the shorter direction.
  • Round-robin scheduling / load balancing. Pick the next worker with (i + 1) % n β€” CPU schedulers, nginx upstreams, task queues.
  • Ring network topologies (SONET/SDH, Token Ring). Traffic between two nodes can travel either arc; pick the shorter healthy one.
  • Games & UI. Circular tracks, carousels, turn order that wraps back to player 0.

If a problem says circular, ring, wrap around, cyclic, rotate, or next … going around β€” this chapter is the toolkit.


3. The circular toolkit (patterns to recognise)

  1. Two directions, then min. Between two points on a ring there are exactly two arcs. Their lengths sum to the whole loop, so other = total βˆ’ arc. Compute one, subtract, take the smaller. (This is the bus-stops problem below.)
  2. "Double it" to linearise. Many circular problems (max circular subarray, next-greater-element-in-a-circular-array) become linear if you imagine the array written twice back-to-back β€” or iterate 2n times using % n instead of actually copying.
  3. Prefix sums on a ring. Range sums that wrap = total βˆ’ (sum of the non-wrapping middle).
  4. Head/tail with modulo (ring buffer). Enqueue at tail = (tail + 1) % n, dequeue at head = (head + 1) % n; track size to tell "full" from "empty".

Decision flow for picking the right circular-array pattern


4. A 30-second worked example (wrap-around distance)

Ring of 5 segment costs gap = [4, 3, 9, 2, 6] (so total = 24). Shortest way from stop 1 to stop 4?

Wrap-around distance on a ring: forward arc 14 vs other arc 10, answer 10

No second loop, no modular gymnastics β€” just one arc and a subtraction. That single trick is the heart of the first problem in this chapter.


5. Problems in this chapter

β–Ά Minimum Distance Between Bus Stops

A circular metro loop; find the shorter of the clockwise / counter-clockwise distance between two stations. Teaches the other = total βˆ’ arc reflex and why reaching for Dijkstra is overkill on a ring.
Pattern: two-directions β†’ min. Target: O(n) time, O(1) space.

(More circular problems β€” circular subarray, ring-buffer design, next greater element II β€” slot in here as the chapter grows; they reuse tools #2–#4 above.)


6. Common pitfalls 🚫

  • Negative modulo when stepping backward β€” use (i - 1 + n) % n.
  • Double-counting the full loop β€” the two arcs already sum to total; don't add the shared endpoints twice.
  • Forgetting start == dest β€” distance is 0, not the whole loop.
  • Actually copying the array to "double" it β€” usually you can just iterate 2n times with % n and save the O(n) space.
  • Off-by-one between "edges" and "nodes" β€” gap[i] is the segment between i and i+1, not a stop itself.

7. Key takeaways

  1. Circular = linear + % n. Master forward/backward stepping and most boundary bugs vanish.
  2. On a ring, there are two arcs; other = total βˆ’ arc turns two traversals into one.
  3. "Double the array" linearises cyclic window / next-greater problems.
  4. Ring buffers are this pattern in production β€” fixed memory, head/tail with modulo.
  5. Recognise the trigger words (circular, wrap, ring, cyclic, rotate) and reach for the toolkit above.

Minimum Distance Between Bus Stops

The one-line idea: on a circle, any two points are joined by exactly two arcs. Add up one arc, and the other is just total βˆ’ arc. The answer is the shorter of the two.


1. The Problem (in plain language)

A city runs a circular metro loop called LoopLine. There are n stations placed around the loop, numbered 0, 1, 2, … , n‑1, and after the last station the track curves back to station 0.

You're given an array gap, where gap[i] is the travel time (in minutes) along the track segment that connects station i to its next neighbour station (i+1) mod n.

A train can run either direction around the loop. Given a start station and a dest station, return the minimum travel time to get from start to dest.

This is a rephrasing of the classic "Distance Between Bus Stops" interview problem β€” but the circular, bidirectional structure is exactly what shows up in real distributed systems (below), so it's worth really understanding rather than memorizing.

Inputs & outputs

Name Meaning
gap gap[i] = cost of the edge between stop i and stop (i+1) mod n
start index of the origin station
dest index of the destination station
return minimum total cost going clockwise or counter‑clockwise

Sign in to continue reading

The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.

Sign in to read the full lesson

Sign in to MAANG.io

Use your Google or Microsoft account β€” no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.