Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
2D Grid String Search
00:00
5 left

2D Grid String Search

HardPython

Problem

Karat's interview evaluation tooling needs to identify every location where a search term appears in a character grid. Given a 2D matrix of characters and a target string, return every path of coordinates whose characters spell the target in order.

A path may move one cell up, down, left, or right at each step. It may not move diagonally, leave the matrix, or reuse a cell within the same path. Return paths in row-major order by their starting coordinate. The order of paths with the same starting coordinate does not matter.

Formal Specification

Implement find_paths(board, target). board is a non-empty rectangular list of lists of one-character strings, and target is a non-empty string. Return a list of paths. Each path is a list of [row, column] coordinate pairs, with one pair for each character in target. Return an empty list if no path exists.

Constraints

  • 1 <= rows, columns <= 8
  • 1 <= len(target) <= rows * columns
  • Every board cell and target character is an uppercase English letter
  • The board is rectangular
  • A cell cannot be reused within one path

Function Signature

def find_paths(board, target):
Interviewer

Your question is 2D Grid String Search. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.