Prime Pairs With Target Sum - Problem
Prime Pairs With Target Sum

You are given an integer n. Your task is to find all pairs of prime numbers that add up to n.

A prime pair (x, y) must satisfy:
• Both x and y are prime numbers
1 ≤ x ≤ y ≤ n
x + y = n

Return a 2D array containing all valid prime pairs [x, y], sorted by increasing order of x. If no prime pairs exist, return an empty array.

Note: A prime number is a natural number greater than 1 that has exactly two factors: 1 and itself.

Input & Output

example_1.py — Basic case
$ Input: n = 12
Output: [[5,7]]
💡 Note: The prime numbers ≤ 12 are: 2, 3, 5, 7, 11. Only the pair (5, 7) satisfies: 5 + 7 = 12, both are prime, and 5 ≤ 7.
example_2.py — Multiple pairs
$ Input: n = 18
Output: [[5,13],[7,11]]
💡 Note: Prime pairs that sum to 18: (5,13) and (7,11). Both pairs satisfy all conditions and are returned in ascending order of the first element.
example_3.py — No pairs exist
$ Input: n = 3
Output: []
💡 Note: No two prime numbers can sum to 3. The only prime ≤ 3 is 2, and 2 + 2 = 4 ≠ 3. Also, we need x ≤ y, so pairs like (1,2) are invalid since 1 is not prime.

Visualization

Tap to expand
Prime Pairs Discovery (n=12)Step 1: Sieve of Eratosthenes123456789101112🟩 Prime 🟥 CompositeStep 2: Prime CollectionPrimes = {2, 3, 5, 7, 11}Step 3: Find Pairs (Two Pointers)Array: [2, 3, 5, 7, 11]Left=2, Right=11: 2+11=13 > 12 → Right--Left=2, Right=7: 2+7=9 < 12 → Left++Left=5, Right=7: 5+7=12 = 12 ✓ → Found [5,7]!Final Result: [[5, 7]]Time: O(n log log n) | Space: O(n)
Understanding the Visualization
1
Sieve Creation
Mark all composite numbers, leaving only primes
2
Prime Collection
Gather all prime numbers in efficient data structure
3
Pair Matching
Use optimal strategy (hash lookup or two pointers) to find sum pairs
Key Takeaway
🎯 Key Insight: Precomputing primes with the Sieve of Eratosthenes transforms an O(n²√n) brute force approach into an efficient O(n log log n) solution.

Time & Space Complexity

Time Complexity
⏱️
O(n log log n)

Sieve takes O(n log log n), finding pairs takes O(π(n)) where π(n) is the number of primes ≤ n

n
2n
Linearithmic
Space Complexity
O(n)

Space for sieve array and hash set to store primes

n
2n
Linearithmic Space

Constraints

  • 1 ≤ n ≤ 106
  • n is guaranteed to be a positive integer
  • Time limit: 2 seconds per test case
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
73.5K Views
Medium Frequency
~15 min Avg. Time
1.8K 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