Ctrl K

Primes Along Grid Rays

Medium
You are given a rectangular grid grid of digits from 1 to 9. From any cell you may cast a ray in one of eight directions (horizontal, vertical or diagonal) and follow it straight to the edge of the grid. Along the way, each digit you pass is appended to a number that begins with the starting cell's digit, and every step produces a new number. For instance, if the ray reads 1, 9, 1, it produces 19 and 191 (the lone starting digit does not count). Over all numbers produced from every cell in every direction, look at the primes greater than 10 and count how many times each one appears. Return the one that appears most often, breaking ties by taking the largest. If there is no such prime, return -1.
Example 1
grid=[[1, 3], [7, 1]] → 71

The rays give 13, 17, 11, 31, 37, 31, 71, 73, 71, 11, 13, 17. All of them are prime; 11, 13, 17, 31 and 71 appear twice each, and the largest of those is 71.

Example 2
grid=[[2, 4, 6]] → -1

Every number longer than one digit here is even, so there is no prime above 10.

Example 3
grid=[[5]] → -1
Constraints
  • 1 ≤ rows, columns ≤ 6
  • 1 ≤ grid[i][j] ≤ 9
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPhoto Frames of the Same Shape MediumEven Piles of Cards EasyCoprime Digit Pairs EasyPair GCDs by Sorted Position HardPrimes Below a Bound Medium
loading Python…
Input
grid=[[1, 3], [7, 1]]
Expected
71

Run checks the first 3 tests in your browser. Submit checks all 55 tests on the server, hidden ones included.