← Questions

Numbers that are a sum of two squares in exactly two ways

0
GoogleCodingLast asked Oct 2025

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] — every m <= n with exactly two pairs 0 <= a <= b and a^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

  • n up 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? Is a = b allowed?
  • 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 <= b with a^2 + b^2 <= n: about π·n/8 pairs, O(n) time, and count per sum in an array of size n + 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 k representations.
  • 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

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding