Leetcode 2761: Prime Pairs With Target Sum

grid47
grid47
Exploring patterns and algorithms
Feb 4, 2024 5 min read

You are given an integer ’n’. Your task is to find all pairs of prime numbers [x, y] such that 1 <= x <= y <= n, x + y = n, and both x and y are prime numbers. Return a 2D sorted list of such prime pairs. If no such pairs exist, return an empty array.
Problem
Approach
Steps
Complexity
Input: The input consists of a single integer 'n'.
Example: n = 12
Constraints:
• 1 <= n <= 10^6
Output: Return a 2D list of prime pairs [x, y], sorted by x. If no pairs exist, return an empty list.
Example: For n = 12, the output is [[5, 7]].
Constraints:
• The pairs must be sorted in increasing order of x.
Goal: Find all prime pairs such that their sum is equal to n.
Steps:
• Generate all prime numbers up to n using the Sieve of Eratosthenes.
• Iterate through the list of primes and check for each pair (x, y) where x + y = n.
• Store all such valid pairs and return them sorted by x.
Goal: The input integer n is between 1 and 10^6. The prime numbers must be less than or equal to n.
Steps:
• 1 <= n <= 10^6
Assumptions:
• The value of n is always a positive integer.
Input: For n = 12
Explanation: The prime numbers less than or equal to 12 are [2, 3, 5, 7, 11]. The valid prime pairs that sum up to 12 are [5, 7].

Input: For n = 30
Explanation: The prime numbers less than or equal to 30 are [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]. The valid prime pairs that sum up to 30 are [7, 23], [11, 19], and [13, 17].

Link to LeetCode Lab


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