Numbers that are a sum of two squares in exactly two ways
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's first round (coding), last asked Oct 2025. It tests math and number theory.
Find every number up to a limit N that can be written as a^2 + b^2 in exactly two different ways. Ways are unordered, so 3^2 + 4^2 and 4^2 + 3^2 are the same way. Agree with the interviewer on whether 0 may be one of the squares; the interface below allows it.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
two_way_sums(n: int) -> list[int]— everym <= nwith exactly two pairs0 <= a <= banda^2 + b^2 = m, in increasing order.
Example
two_way_sums(100) -> [25, 50, 65, 85, 100]
# 25 = 0² + 5² = 3² + 4² 50 = 1² + 7² = 5² + 5²
# 65 = 1² + 8² = 4² + 7² 85 = 2² + 9² = 6² + 7²
# 100 = 0² + 10² = 6² + 8²
If zero is not allowed (1 <= a <= b), the answer up to 100 is [50, 65, 85].
Constraints
-
nup to about 10^7 for the counting approach; discuss what changes at 10^12.
Clarifying questions
- Are
(a, b)and(b, a)the same way? Is zero allowed? Isa = ballowed? - Exactly two ways, or at least two?
- How large is the limit, and is memory bounded?
- Should the output include the pairs, or only the numbers?
What a strong answer covers
- Enumerate pairs
a <= bwitha^2 + b^2 <= n: aboutπ·n/8pairs, O(n) time, and count per sum in an array of sizen + 1(or a hash map when sums are sparse). - Avoid the O(n · sqrt(n)) "for each m, try every a" approach, or argue when it is acceptable because it needs no array.
- Integer square roots done exactly (
isqrt), never with floating point near perfect squares. - Memory: an array of small counters, capped at 3 so they fit in a byte.
- The number-theory view: the count of representations follows from the prime factorisation (primes
≡ 1 mod 4), which gives an answer per number without enumeration.
Follow-ups
- Return the numbers with at least
krepresentations. - The limit is 10^12: enumerate pairs in blocks of sums, or use the factorisation rule.
- Sums of two cubes in two ways (the taxicab numbers).
Where it's asked
- Google · First round: coding · Last asked Oct 202545 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
What it tests
math · number theory
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
