Prime Pairs With Target Sum - Problem
Prime Pairs With Target Sum
You are given an integer
A prime pair
• Both
•
•
Return a 2D array containing all valid prime pairs
Note: A prime number is a natural number greater than 1 that has exactly two factors: 1 and itself.
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 = nReturn 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
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
⚡ Linearithmic
Space Complexity
O(n)
Space for sieve array and hash set to store primes
⚡ Linearithmic Space
Constraints
- 1 ≤ n ≤ 106
- n is guaranteed to be a positive integer
- Time limit: 2 seconds per test case
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code