LeetCode 2614: Prime In Diagonal Solution
Master LeetCode problem 2614 (Prime In Diagonal), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2614. Prime In Diagonal
Problem Explanation
Explanation:
To solve this problem, we will iterate over the diagonals of the given 2D array nums and keep track of the largest prime number found. We will implement a helper function to check if a number is prime or not. Then, we will traverse the main diagonal and the secondary diagonal to find the largest prime number.
- Start by defining a helper method
isPrimeto check if a number is prime or not. - Iterate over the main diagonal and secondary diagonal of the 2D array
nums. - For each number encountered in the diagonals, check if it is prime and update the largest prime found so far.
- Return the largest prime number found or 0 if no prime number is present on any of the diagonals.
Time Complexity: O(n), where n is the size of the input array nums.
Space Complexity: O(1).
:
Solution Code
class Solution {
public boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public int largestPrimeDiagonal(int[][] nums) {
int largestPrime = 0;
for (int i = 0; i < nums.length; i++) {
if (isPrime(nums[i][i])) {
largestPrime = Math.max(largestPrime, nums[i][i]);
}
if (isPrime(nums[i][nums.length - i - 1])) {
largestPrime = Math.max(largestPrime, nums[i][nums.length - i - 1]);
}
}
return largestPrime;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2614 (Prime In Diagonal)?
This page provides optimized solutions for LeetCode problem 2614 (Prime In Diagonal) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2614 (Prime In Diagonal)?
The time complexity for LeetCode 2614 (Prime In Diagonal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2614 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2614 in Java, C++, or Python.