FastPrepCogwheel Rotation Directions

Cogwheel Rotation Directions

OpenAI logoOpenAI● MediumINTERNOA
Learn

Problem statement

You are given nCogwheels gears numbered from 0 to nCogwheels - 1 and a list of connections. Each connection [u, v] means that gears u and v mesh with each other. All gears belong to one connected undirected graph, so every gear is reachable from gear 0.

Gear 0 is driven clockwise. Two connected gears must rotate in opposite directions.

Return an array [clockwiseCount, counterclockwiseCount] containing the number of gears rotating in each direction. If the connections make these requirements inconsistent and the mechanism locks, return [-1, -1].

Function

countRotations(nCogwheels: int, connections: int[][]) → int[]

Examples

Example 1

nCogwheels = 5connections = [[0,1],[1,2],[2,3],[3,4],[0,3]]return = [3,2]

Gears 0, 2, 4 rotate clockwise, and gears 1, 3 rotate counterclockwise. Every connected pair rotates oppositely, so the result is [3, 2].

Example 2

nCogwheels = 3connections = [[0,1],[1,2],[0,2]]return = [-1,-1]

Gear 1 must rotate counterclockwise, so gear 2 must rotate clockwise through connection [1, 2]. But connection [0, 2] requires gear 2 to rotate counterclockwise. The contradiction locks the mechanism.

Example 3

nCogwheels = 5connections = [[0,1],[0,2],[0,3],[0,4]]return = [1,4]

Gear 0 rotates clockwise. All four other gears connect directly to it and rotate counterclockwise.

Constraints

  • 1 <= nCogwheels <= 1000.
  • Each connection contains two valid gear indices.
  • The connections form one connected undirected graph.
  • Gear 0 rotates clockwise.

More OpenAI problems

See OpenAI hiring insights
public int[] countRotations(int nCogwheels, int[][] connections) {
    // Return clockwise and counterclockwise counts, or [-1, -1].
}
nCogwheels5
connections[[0,1],[1,2],[2,3],[3,4],[0,3]]
expected[3,2]
Checking account…