KatInterview

Circular Token Distribution on a Ring of Nodes

Arrays & HashingModel answer
MediumModel answerArrays & Hashingarraysmathmodulo arithmetic

Last updated

Distribute k tokens clockwise across n nodes in a ring starting at a given index, returning each node's final count without simulating one token at a time.

Problem

You have n nodes arranged in a ring, each holding some number of tokens. Given an array nodes where nodes[i] is the current token count at node i, you need to deliver exactly k new tokens into the ring.

Delivery works like this: starting at start_index, place one token at the current node, then advance clockwise. After the last node (n-1), wrap back to node 0. Repeat until all k tokens have been placed.

Return the state of nodes after all k tokens are delivered.

Function Signature

def deliver_tokens(nodes: List[int], k: int, start_index: int) -> List[int]:

Constraints

  • 1 ≤ n ≤ 10^5
  • 0 ≤ k ≤ 10^18
  • 0 ≤ nodes[i] ≤ 10^9

Examples

Example 1

nodes = [1, 2, 3],  k = 4,  start_index = 1

Step 1 → index 1: [1, 3, 3]
Step 2 → index 2: [1, 3, 4]
Step 3 → index 0: [2, 3, 4]
Step 4 → index 1: [2, 4, 4]

Output: [2, 4, 4]

Example 2

nodes = [0, 0],  k = 5,  start_index = 0

Output: [3, 2]

What is expected

  • A solution that handles k up to 10^18 efficiently — a step-by-step simulation will not pass within time limits.
  • Correct wrap-around behaviour regardless of where start_index falls.
  • Proper handling of edge cases: empty input, k = 0, k that is a multiple of n, and n = 1.

Hints

Hint 1

Think about what happens after exactly n deliveries. Every node has received the same number of tokens regardless of where you started. Can you use that periodicity to skip most of the work?

Hint 2

Split k into a quotient and a remainder using integer division by n. The quotient tells you how many complete laps happen; the remainder tells you which nodes get one extra token on the final partial lap.

Hint 3

The remainder tokens go to consecutive nodes starting at start_index. Use modulo arithmetic to handle the wrap-around cleanly, and watch out for the empty-array case before you divide by n.