Problem · Matrix

Push and Fall Boxes

Learn this problem
MediumDatabricks logoDatabricksOA

Problem statement

You are given a matrix of characters representing a board. Each cell contains one of three characters:

  • '-', which means that the cell is empty.
  • '*', which means that the cell contains an obstacle.
  • '#', which means that the cell contains a box.

Perform the following operations in order:

  1. First, push the boxes to the right as far as possible. Each box moves right until it hits an obstacle, another box, or the right edge of the board.
  2. Then, push the boxes down as far as possible. Each box moves down until it hits an obstacle, another box, or the bottom of the board.

Given board, return the state of the board after the push and fall operations.

A solution with time complexity no worse than O(board.length * board[0].length * min(board.length, board[0].length)) will fit within the execution time limit.

Function

pushAndFall(board: char[][]) → char[][]

Examples

Example 1

board = [["-","#","-","-","-"],["-","-","-","-","-"],["#","-","#","#","-"],["#","-","-","-","#"]]return = [["-","-","-","-","-"],["-","-","-","-","#"],["-","-","-","#","#"],["-","-","#","#","#"]]

After the right push, the rows become ----#, -----, --###, and ---##. The downward push then packs the boxes at the bottoms of their columns, producing the shown board.

Constraints

  • board is a rectangular matrix.
  • Each cell is one of '-', '*', or '#'.
  • A solution with time complexity no worse than O(board.length * board[0].length * min(board.length, board[0].length)) fits within the execution time limit.

More Databricks problems

drafts saved locally
public char[][] pushAndFall(char[][] board) {
  // write your code here
}
board[["-","#","-","-","-"],["-","-","-","-","-"],["#","-","#","#","-"],["#","-","-","-","#"]]
expected[["-","-","-","-","-"],["-","-","-","-","#"],["-","-","-","#","#"],["-","-","#","#","#"]]
checking account