FastPrepCount Straight-Line Word Occurrences in a Grid

Count Straight-Line Word Occurrences in a Grid

Optiver logoOptiver● MediumFULLTIMEOA
Learn

Problem statement

Given a rectangular grid of characters and a nonempty word, count every occurrence that lies entirely in one row or one column.

Search left to right, right to left, top to bottom, and bottom to top. Matches may overlap and characters are compared exactly. When the word has length one, count each matching cell once rather than once per direction.

Function

countStraightWords(grid: String[], word: String) → int

Examples

Example 1

grid = ["ABCA","BCAB","CABC"]word = "ABC"return = 4

There are two left-to-right row matches and two top-to-bottom column matches.

Example 2

grid = ["AAAA"]word = "AAA"return = 4

Two overlapping matches appear in each horizontal direction.

Example 3

grid = ["AX","YA"]word = "A"return = 2

Each matching cell is counted once for a one-character word.

Constraints

  • 1 <= grid.length, grid[i].length <= 500.
  • All rows have equal length.
  • 1 <= word.length <= 500.
  • The grid and word contain visible ASCII characters.

More Optiver problems

See Optiver hiring insights
public int countStraightWords(String[] grid, String word) {
    // Write your solution here.
}
grid["ABCA","BCAB","CABC"]
word"ABC"
expected4
Checking account…