Leetcode 2614: Prime In Diagonal

grid47
grid47
Exploring patterns and algorithms
Feb 19, 2024 6 min read

Given a 2D grid of integers, you need to determine the largest prime number present on any of the diagonals of the grid. A number is considered prime if it is greater than 1 and divisible only by 1 and itself. The diagonal elements are those where the row and column indices are the same or sum to the length of the grid minus 1.
Problem
Approach
Steps
Complexity
Input: You are given a square grid of integers 'nums', represented as a 2D array. Each element in nums is an integer between 1 and 4*10^6.
Example: nums = [[2, 3, 5], [7, 11, 13], [17, 19, 23]]
Constraints:
• 1 <= nums.length <= 300
• nums.length == numsi.length
• 1 <= nums[i][j] <= 4 * 10^6
Output: Return the largest prime number present on any of the diagonals in the grid. If no prime number is found, return 0.
Example: Output: 23
Constraints:
• The output is a single integer representing the largest prime number on the diagonals, or 0 if none is found.
Goal: The goal is to find the largest prime number that appears on at least one diagonal of the matrix.
Steps:
• Step 1: Loop through the grid and check both diagonals (top-left to bottom-right and top-right to bottom-left).
• Step 2: For each number on the diagonals, check if it is prime.
• Step 3: Keep track of the largest prime number encountered.
• Step 4: Return the largest prime, or 0 if no prime is found.
Goal: Ensure the solution handles matrices of varying sizes efficiently, and works within the constraints of the input values.
Steps:
• The matrix is square, so the number of rows equals the number of columns.
• The integers in the matrix range from 1 to 4*10^6.
Assumptions:
• You can assume the matrix will be square (same number of rows and columns).
• The elements are integers, and the prime check will be done for values between 1 and 4*10^6.
Input: nums = [[2, 3, 5], [7, 11, 13], [17, 19, 23]]
Explanation: The diagonals are [2, 11, 23] and [5, 11, 17]. The prime numbers on these diagonals are 2, 11, 17, 23, and the largest prime is 23.

Input: nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Explanation: The diagonals are [1, 5, 9] and [3, 5, 7]. The prime numbers are 5 and 7, and the largest prime is 7.

Link to LeetCode Lab


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