FastPrepAscend Vertical Wall (For off-campus 2025 batch hiring :)

Ascend Vertical Wall (For off-campus 2025 batch hiring :)

Uber logoUber● MediumNEW GRADOA

Updated

Problem statement

A robot with battery capacity w wants to climb a vertical wall made of N rows and M columns of cells. wall[0] is the top row and wall[N - 1] is the bottom row. Each cell is "x", meaning the robot can stand on it, or ".", meaning it cannot.

The robot starts on any "x" cell of the bottom row and wants to reach any "x" cell of the top row. It moves by hops. A hop from cell (r1, c1) to cell (r2, c2) (row, column) is allowed only when all of these hold:

  • The target cell is "x". The cells in between do not matter.
  • The robot never moves down: r2 ≤ r1. It may hop sideways along the same row, straight up, or diagonally up.
  • The Euclidean distance between the two cells is at most w: (r1 - r2)2 + (c1 - c2)2 ≤ w2.
  • Because of a sensor limit, a hop moves at most 2 columns sideways: |c1 - c2| ≤ 2.

Return the minimum number of hops needed to get from the bottom row to the top row, or -1 if it is not possible. If the wall has only one row, the answer is 0 when that row has an "x" cell.

Complete the function canAscend in the editor.

canAscend has the following parameters:

  • String[][] wall: the wall, top row first; each cell is "x" or "."
  • int w: the battery capacity (the longest hop allowed)

The function returns an int: the minimum number of hops, or -1 if the robot cannot reach the top row.

Function

canAscend(wall: String[][], w: int) → int

Examples

Example 1

wall = [["x", "x", ".", "x"], [".", "x", ".", "."], [".", "x", ".", "x"]]w = 1return = 2

The wall has 3 rows and 4 columns, and w = 1. With w = 1, a hop can only go to a neighboring cell: one row up or one column sideways.

Start at the bottom-row cell (2, 1), hop up to (1, 1), then hop up to (0, 1) in the top row. That is 2 hops. Each hop climbs at most 1 row and the robot must climb 2 rows, so 2 is the minimum.

Example 2

wall = [[".", ".", "x"], [".", "x", "."], ["x", ".", "."]]w = 2return = 2

The only bottom-row cell is (2, 0) and the only top-row cell is (0, 2). A direct hop has distance √(22 + 22) = √8, which is more than w = 2.

Instead, hop diagonally to (1, 1) (distance √2), then diagonally to (0, 2) (distance √2). That is 2 hops.

Constraints

  • 1 ≤ N ≤ 50, where N = wall.length
  • 1 ≤ M ≤ 50, where M = wall[i].length for every row
  • Each wall[i][j] is "x" or ".".
  • 1 ≤ w ≤ 50

More Uber interview questions

Similar questions at other companies

All Uber interview questionsSee Uber hiring insights
Saved
class Solution {
    public int canAscend(String[][] wall, int w) {
      // write your code here
    }

}
Checking account…