Prime Pairs With Target Sum - Problem

You are given an integer n. We say that two integers x and y form a prime number pair if:

  • 1 <= x <= y <= n
  • x + y == n
  • x and y are prime numbers

Return the 2D sorted list of prime number pairs [xi, yi]. The list should be sorted in increasing order of xi. If there are no prime number pairs at all, return an empty array.

Note: A prime number is a natural number greater than 1 with only two factors, itself and 1.

Input & Output

Example 1 — Basic Case
$ Input: n = 12
Output: [[5,7]]
💡 Note: The prime numbers ≤ 12 are: 2, 3, 5, 7, 11. We need pairs that sum to 12: 5 + 7 = 12, and both 5 and 7 are prime, so return [[5,7]].
Example 2 — Multiple Pairs
$ Input: n = 20
Output: [[3,17],[7,13]]
💡 Note: Prime numbers ≤ 20: 2, 3, 5, 7, 11, 13, 17, 19. Valid pairs summing to 20: 3+17=20 and 7+13=20. Both pairs have prime numbers.
Example 3 — No Valid Pairs
$ Input: n = 4
Output: []
💡 Note: Only primes ≤ 4 are 2 and 3. We need pairs summing to 4: 2+2=4, but we need x ≤ y and distinct pairs. No valid pairs exist.

Constraints

  • 2 ≤ n ≤ 106

Visualization

Tap to expand
Prime Pairs With Target Sum INPUT n = 12 Numbers from 1 to 12: 1 2 3 4 5 6 7 8 9 10 11 12 Prime Not Prime Goal: Find prime pairs (x,y) where x + y = 12 Primes: 2, 3, 5, 7, 11 Condition: x <= y ALGORITHM STEPS 1 Sieve of Eratosthenes Generate primes up to n isPrime[] = [F,F,T,T,F,T, F,T,F,F,F,T,F] 2 Iterate x from 2 to n/2 x ranges: 2, 3, 4, 5, 6 3 Check Both Primes If isPrime[x] AND isPrime[n-x] x=2: 2+10=12 (10 not prime) NO x=3: 3+9=12 (9 not prime) NO x=4: (4 not prime) SKIP x=5: 5+7=12 (both prime) OK x=6: (6 not prime) SKIP 4 Add Valid Pair Store [5, 7] in result FINAL RESULT Prime Pair Found: 5 + 7 = 12 Output: [[5, 7]] OK - 1 Pair Found 5 is prime, 7 is prime 5 + 7 = 12, 5 <= 7 Key Insight: The Sieve of Eratosthenes pre-computes all primes up to n in O(n log log n) time. We only need to check x from 2 to n/2 since pairs (x,y) and (y,x) are equivalent when x <= y. For each prime x, we check if (n-x) is also prime using O(1) lookup in our sieve array. Total complexity: O(n log log n) for sieve + O(n) for pair finding = O(n log log n) TutorialsPoint - Prime Pairs With Target Sum | Sieve of Eratosthenes Approach
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen