Leetcode 3044: Most Frequent Prime

grid47
grid47
Exploring patterns and algorithms
Jan 7, 2024 8 min read

You are given a matrix of integers, where each cell contains a digit from 1 to 9. Starting from any cell in the matrix, you can move in one of eight possible directions (east, south-east, south, south-west, west, north-west, north, and north-east) and create numbers by appending the digits along the path. For each valid path, numbers greater than 10 are generated. The task is to find the most frequent prime number greater than 10 among all the numbers generated by traversing the matrix. If there are multiple such prime numbers, return the largest one. If no prime number exists, return -1.
Problem
Approach
Steps
Complexity
Input: You are given a 2D matrix 'mat' of size m x n, where 1 <= m, n <= 6, and each element in mat is between 1 and 9 (inclusive).
Example: mat = [[2, 3, 4], [5, 6, 7], [8, 9, 1]]
Constraints:
• 1 <= m, n <= 6
• 1 <= mat[i][j] <= 9
Output: Return the most frequent prime number greater than 10 formed by traversing the matrix. If no such prime exists, return -1.
Example: For mat = [[2, 3, 4], [5, 6, 7], [8, 9, 1]], the output is 23.
Constraints:
Goal: Traverse the matrix from each cell, generate numbers by moving in any of the 8 directions, and identify the most frequent prime number greater than 10.
Steps:
• 1. Define directions for traversal (east, south-east, south, etc.).
• 2. For each cell, generate numbers by moving in the defined directions.
• 3. Check if the generated number is a prime number greater than 10.
• 4. Keep track of the frequency of prime numbers.
• 5. Return the most frequent prime number greater than 10. If there are multiple such numbers, return the largest one. If none exists, return -1.
Goal: The constraints are as follows:
Steps:
• Matrix size is at most 6x6.
• The digits in each cell of the matrix are between 1 and 9.
Assumptions:
• You can move in one of eight possible directions from any cell.
• Numbers are formed by traversing through consecutive cells in a chosen direction.
Input: For the input matrix mat = [[2, 3, 4], [5, 6, 7], [8, 9, 1]]
Explanation: Start from each cell and move in all 8 possible directions. The numbers greater than 10 are generated. Among these, the prime number 23 appears the most frequently, so the output is 23.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus