Databricks questions

K in a Row

DatabricksOnsiteHard

Build Game, a generalized tic-tac-toe on a board with rows rows and cols columns, numbered from 0. Two players, 1 and 2, place marks. A player wins by getting k or more of their own marks in an unbroken line horizontally, vertically, or along either diagonal.

The constructor takes rows, cols and k. Each call to move(row, col, player) places player's mark on an empty cell and returns player if that mark completes a winning line (a line of at least k of their marks that includes the new mark), or 0 otherwise. Players do not have to alternate, a cell is never played twice, and no move is made after a win.

Each test drives one Game(rows, cols, k) instance through a sequence of moves and checks every return value.

Part 1: Small board

Implement move(row, col, player). row and col are the coordinates of an empty cell, player is 1 or 2. Place the mark and return player if it completes a line of at least k of that player's marks through the new cell, or 0 otherwise.

Only the line through the new mark can create a win, so you do not need to look at the rest of the board.

  1. Example 1
    init
    [3,3,3]
    operations
    [["move",[0,0,1]],["move",[0,1,2]],["move",[1,1,1]],["move",[0,2,2]],["move",[2,2,1]]]
    Output
    [0,0,0,0,1]

    Why: Player 1 places (0,0), (1,1) and then (2,2), a full main diagonal, so the fifth move returns 1. The earlier moves return 0.

Constraints

  • 1 <= rows, cols <= 50
  • 1 <= k <= max(rows, cols)
  • 1 <= player <= 2
  • 1 <= len(operations) <= rows * cols
  • 0 <= row < rows and 0 <= col < cols
  • each move targets a cell no earlier move in the same test targeted
  • at most one move returns a nonzero value, and it is the last one
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
K in a Row: Databricks interview question | LoopCoach