Problem · Array

Enumerate Character Paths to a Marker

Learn this problem
MediumTesla logoTeslaFULLTIMEONSITE INTERVIEW

Problem statement

Given a non-empty rectangular matrix grid whose cells contain either a one-character string or the marker "*", enumerate every simple path from (0, 0) to the marker.

A move goes to an orthogonally adjacent cell, and a path may not visit the same cell twice. Each visited character cell contributes its character to the path string. The marker terminates the path and contributes no character. If grid[0][0] is the marker, the only result is the empty string.

Return all collected strings in lexicographic order. Keep duplicate strings when distinct paths produce the same characters.

Function

enumeratePaths(grid: String[][]) → List<String>

Examples

Example 1

grid = [["a","b"],["c","*"]]return = ["ab","ac"]

The two simple paths are right then down, producing ab, and down then right, producing ac.

Example 2

grid = [["*"]]return = [""]

The starting cell is terminal, so the one path collects no characters.

Example 3

grid = [["a","a","*"]]return = ["aa"]

The single orthogonal path collects both character cells before reaching the marker.

Constraints

  • 1 <= grid.length and 1 <= grid[i].length.
  • Every row has the same length.
  • The matrix contains at most 20 cells.
  • Exactly one cell contains "*".
  • Every other cell contains a single lowercase English letter.
  • The number of returned paths fits in memory.

More Tesla problems

drafts saved locally
public List<String> enumeratePaths(String[][] grid) {
  // write your code here
}
grid[["a","b"],["c","*"]]
expected["ab","ac"]
checking account