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: n = 12Find all prime pairs [x, y] where x + y = 12Step 1: Identify all prime numbers ≤ 12Numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12Primes: 2, 3, 5, 7, 11Step 2: Check all possible pairs that sum to 122+10=12 (10 not prime), 3+9=12 (9 not prime), 5+7=12 (both prime!) ✓Continue checking: 6+6, 7+5 (already found), etc.Step 3: Output[[5, 7]]
Understanding the Visualization
1
Input
Given integer n, find prime pairs [x,y] where x+y=n
2
Process
Identify all primes ≤ n and check valid pairs
3
Output
Return sorted list of prime pairs
Key Takeaway
🎯 Key Insight: Use Sieve of Eratosthenes to precompute primes, then efficiently check complementary pairs
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