#3044

Most Frequent Prime

Medium
ArrayHash TableMathMatrixCountingEnumerationNumber TheoryHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n²)
💡

Intuition

Time O(n²)Space O(n²)

We can optimize the brute force approach by using memoization to avoid recalculating paths from the same cell, thus reducing redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a memoization table to store results of previously computed paths from each cell.
  2. 2Step 2: For each cell, if the result is already computed, return it instead of recalculating.
  3. 3Step 3: After generating all numbers, filter for primes and find the most frequent one.
solution.py37 lines
1from collections import defaultdict
2
3class Solution:
4    def mostFrequentPrime(self, mat):
5        directions = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)]
6        prime_count = defaultdict(int)
7        primes = set()
8        memo = {}  # Memoization table
9
10        def is_prime(num):
11            if num < 2:
12                return False
13            for i in range(2, int(num**0.5) + 1):
14                if num % i == 0:
15                    return False
16            return True
17
18        def dfs(x, y, num):
19            if (x, y, num) in memo:
20                return memo[(x, y, num)]
21            if num > 10 and is_prime(num):
22                prime_count[num] += 1
23                primes.add(num)
24            for dx, dy in directions:
25                nx, ny = x + dx, y + dy
26                if 0 <= nx < len(mat) and 0 <= ny < len(mat[0]):
27                    dfs(nx, ny, num * 10 + mat[nx][ny])
28            memo[(x, y, num)] = prime_count
29            return prime_count
30
31        for i in range(len(mat)):
32            for j in range(len(mat[0])):
33                dfs(i, j, mat[i][j])
34
35        if not primes:
36            return -1
37        return max(prime_count, key=lambda x: (prime_count[x], x))

Complexity note: The time complexity remains O(n²) as we still explore all cells, but memoization helps avoid redundant calculations. The space complexity increases to O(n²) due to the memoization table storing results for each cell.

  • 1Understanding how to traverse a 2D matrix in multiple directions is crucial for this problem.
  • 2Recognizing prime numbers and efficiently counting their occurrences can significantly impact performance.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.