Leetcode 2614. Prime In Diagonal
2614. Prime In Diagonal
You are given a 2D matrix grid
of size n x n
. Return the largest prime number that lies on either of the two diagonals of grid
. In case, no prime number is present on the diagonals, return 0.
A prime number is a natural number greater than 1 which is only divisible by 1 and itself.
A number x
is said to be on a diagonal if there exists some index i
for which any of the following is true:
n x n
)?
n x n
.n
? Is it controlled within a specific range?
n
can vary but is typically manageable within the constraints of computational limits for interviews, say, from 1
to 1000
.grid[i][i]
for i
in 0
to n-1
.grid[i][n-i-1]
for i
in 0
to n-1
.isPrime(int num)
to determine if a number is prime.#include <vector>
#include <cmath>
#include <algorithm> // for max function
bool isPrime(int num) {
// Any number less than 2 is not a prime number
if (num < 2) return false;
// Check for factors from 2 up to the square root of num
for (int i = 2; i <= std::sqrt(num); ++i) {
if (num % i == 0) return false;
}
return true;
}
int largestPrimeInDiagonals(const std::vector<std::vector<int>>& grid) {
int n = grid.size();
int largest_prime = 0;
for (int i = 0; i < n; ++i) {
int top_left_diag = grid[i][i];
int top_right_diag = grid[i][n - i - 1];
if (isPrime(top_left_diag)) {
largest_prime = std::max(largest_prime, top_left_diag);
}
if (isPrime(top_right_diag)) {
largest_prime = std::max(largest_prime, top_right_diag);
}
}
return largest_prime;
}
2 * n
elements.isPrime
function will run at worst O(√m), where m
is the number being checked.
Thus, the approach remains efficient within the typical constraints of interview problems and ensures we quickly determine the largest prime present on the diagonals.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?