FastPrepValidate a Nonogram Grid

Validate a Nonogram Grid

Karat logoKarat● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given a rectangular binary matrix and a clue list for every row and column, return whether all clues describe the matrix exactly. 0 is black and 1 is white.

Read rows left to right and columns top to bottom. Each clue lists, in order, the lengths of maximal contiguous black runs. Separate runs require at least one white cell; leading and trailing white cells do not create runs. An empty clue list [] describes an entirely white line.

For example, the row clue [2,1] matches [1,0,0,1,0], [0,0,1,1,0] and [0,0,1,0,1]. It does not match [1,0,1,0,0] because the run order is reversed, or [1,0,0,0,1] because the black cells form one run of length three.

Validate the supplied clues as they are; do not change them to fit the grid. All row clues and all column clues must match.

Function

validateNonogram(matrix: int[][], rowClues: int[][], columnClues: int[][]) → boolean

Examples

Example 1

matrix = [[1,1,1,1],[0,1,1,1],[0,1,0,0],[1,1,0,1],[0,0,1,1]]rowClues = [[],[1],[1,2],[1],[2]]columnClues = [[2,1],[1],[2],[1]]return = true

Every ordered run list matches. The first row has no black cells and uses an empty list.

Example 2

matrix = [[1,1,1,1],[0,1,1,1],[0,1,0,0],[1,1,0,1],[0,0,1,1]]rowClues = [[],[],[1],[1],[1,1]]columnClues = [[2],[1],[2],[1]]return = false

The second row contains one black run, but its supplied row clue is empty. Other mismatches also occur.

Example 3

matrix = [[1,1],[0,0],[0,0],[1,0]]rowClues = [[],[2],[2],[1]]columnClues = [[1,1],[3]]return = false

The first column is [1,0,0,1], which has one run of length 2, not two separated runs of length 1. The original negative result is correct.

Constraints

  • For this exercise, assume a rectangular matrix with 1 <= R,C <= 30 and cells in {0,1}.
  • rowClues has exactly R lists and columnClues has exactly C lists.
  • For this exercise, assume each clue list has at most its line’s length entries, all positive integers no greater than that line’s length. Clues may be infeasible and should then return false.
  • K denotes the total number of entries in all supplied clue lists. Empty lists are allowed; [0] is outside the input contract.

More Karat problems

See Karat hiring insights
public boolean validateNonogram(int[][] matrix, int[][] rowClues, int[][] columnClues) {
    // Write your code here.
    return false;
}
matrix[[1,1,1,1],[0,1,1,1],[0,1,0,0],[1,1,0,1],[0,0,1,1]]
rowClues[[],[1],[1,2],[1],[2]]
columnClues[[2,1],[1],[2],[1]]
expectedtrue
Checking account…