← Questions

Count gears turning each way in a meshed gear train, or detect a jam

0
OpenAICodingLast asked Mar 2026

A mechanism has n gears numbered 0 to n - 1. Each connection [u, v] means gears u and v mesh, and every gear can be reached from gear 0 through connections. Gear 0 is driven clockwise, and two meshing gears always turn in opposite directions. Count how many gears turn each way, or report that the mechanism jams because the directions contradict each other.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • gear_directions(n: int, connections: list[list[int]]) -> list[int]: returns [clockwise, counterclockwise], or [-1, -1] when no consistent assignment exists.

Example

n = 6, connections = [[0,1],[1,2],[2,3],[3,0],[2,4],[4,5]]  ->  [3, 3]
# clockwise: 0, 2, 5   counterclockwise: 1, 3, 4

n = 4, connections = [[0,1],[1,2],[2,0],[2,3]]  ->  [-1, -1]
# 0, 1, 2 form a loop of three gears: 2 must oppose both 0 and 1, which already oppose each other

n = 1, connections = []  ->  [1, 0]

Constraints

  • 1 <= n <= 1000.
  • Every index in connections is a valid gear, and the graph is connected.

Clarifying questions

  • Can a connection list a gear meshing with itself, or the same pair twice?
  • Is the graph really guaranteed connected, or should gears not reachable from 0 be counted somehow?
  • Should a jam return [-1, -1], raise, or return which connection caused it?

What a strong answer covers

  • Seeing this as two-coloring an undirected graph: BFS or DFS from gear 0, giving each new neighbor the opposite direction.
  • Detecting a jam when an edge joins two gears of the same direction (an odd cycle), and stopping early.
  • An adjacency list and O(n + m) time and memory; an iterative traversal so deep chains don't overflow the stack.
  • Tests: a single gear, a star, an even loop, an odd loop, a self-loop.

Follow-ups

  • The graph may have several components and only gear 0 is driven. What do you report for the rest?
  • Gears have tooth counts. Return each gear's speed relative to gear 0, and detect a jam when two paths give different speeds.
  • Connections arrive one at a time. Report the first connection that jams the mechanism (union-find with parity).
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding