Prime Pairs With Target Sum — LeetCode 2761 Python Solution

MediumArrayMathEnumerationNumber Theory
Problem
#2761
Reading time
3 min

The 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].

Example

Input
n = 10
Output
[[3,7],[5,5]]
Explanation
In this example, there are two prime pairs that satisfy the criteria.

Python solution

Python
class Solution:
    def findPrimePairs(self, n: int) -> List[List[int]]:
        primes = [True] * n
        for i in range(2, n):
            if primes[i]:
                for j in range(i + i, n, i):
                    primes[j] = False
        ans = []
        for x in range(2, n // 2 + 1):
            y = n - x
            if primes[x] and primes[y]:
                ans.append([x, y])
        return ans

Complexity

MeasureComplexity
TimeO(n \log \log n)
SpaceO(n), where n is the number given in the problem auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2761. Prime Pairs With Target Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Number Theory.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2761. Prime Pairs With Target Sum?
LeetCode 2761. Prime Pairs With Target Sum is rated Medium on LeetCode.
What is the time complexity of LeetCode 2761. Prime Pairs With Target Sum?
The Python solution on this page runs in O(n \log \log n).
What is the space complexity of LeetCode 2761. Prime Pairs With Target Sum?
The Python solution on this page uses O(n), where n is the number given in the problem auxiliary space.
What topics does LeetCode 2761. Prime Pairs With Target Sum cover?
LeetCode 2761. Prime Pairs With Target Sum is tagged Array, Math, Enumeration and Number Theory on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview