FastPrepCount Straight-Line Word Occurrences in a Grid
Problems/Count Straight-Line Word Occurrences in a Grid

Count Straight-Line Word Occurrences in a Grid

Optiver logoOptiver● MediumFULLTIMEOA
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interview report supplies a character matrix, target word, occurrence count, and the restriction that a match remain horizontal or vertical without turning. It omits direction, overlap, character, bound, and interface rules; the practice contract makes those choices explicit. The judged task matches the report at about 86%.

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

  • Power Cell BankOA · Seen Nov 2026
  • Overheat Prevention ControllerOA · Seen Oct 2026
  • Fastest Average Speed over a Rolling KilometerOA · Seen Sep 2026
All Optiver interview questionsSee Optiver hiring insights
Saved
class Solution {
    public int countStraightWords(String[] grid, String word) {
        // Write your solution here.
    }
}
Checking account…