Problem Description
Given a m x n matrix of digits, form numbers by moving in any one of eight fixed directions (without changing direction) starting from any cell. At every step of the path (each digit appended), a new number is formed. Among those numbers that are greater than 10, find all prime numbers, count their frequencies, and return the most frequent prime. In case of frequency ties, return the largest prime. If no such prime exists, return -1.
Key Insights
- Use eight fixed directions (east, south-east, south, south-west, west, north-west, north, north-east) for path traversal.
- Generate numbers step-by-step along each path; check numbers as soon as they exceed 10.
- A helper function is needed to verify if a number is prime.
- Maintain a frequency dictionary (hash table) to count how many times each prime appears.
- After processing all cells and directions, select the prime with the highest frequency (and largest value in case of ties).
Space and Time Complexity
Time Complexity: O(m * n * L * sqrt(V)) where L is the maximum length of a path (bounded by grid dimensions) and V is the value of the formed number (with prime checking up to sqrt(V)). Space Complexity: O(P) where P is the number of primes found, stored in a dictionary. Given the tight grid constraints, this is acceptable.
Solution
To solve the problem:
- Iterate over each cell in the matrix.
- For each cell, explore all 8 directions.
- For each direction, build the number step-by-step by iterating until the next cell is out-of-bound.
- Once a new digit is added forming a number greater than 10, check if it’s prime. If so, record its frequency in a dictionary.
- After processing all paths, inspect the dictionary to find the prime with the highest frequency. If there's a tie, choose the largest prime among them.
- Return the identified prime. If no prime number greater than 10 was found, return -1.