Skip to content
Problem 633 · LeetCode 633(opens in a new tab)

Sum of Square Numbers

MediumMath

You are given a whole number c that is zero or more. Decide whether it can be written as a² + b², where a and b are whole numbers (zero is allowed, and a may equal b).

Return true if such a pair exists, otherwise false.

Example 1

Input:  c = 41
Output: true
Why:    16 + 25 = 41, so a = 4 and b = 5
2 more examples and the constraints

Example 2

Input:  c = 7
Output: false
Why:    the squares up to 7 are 0, 1 and 4; no two make 7

Example 3

Input:  c = 0
Output: true
Why:    0² + 0² = 0

Constraints

  • 0 ≤ c ≤ 2,147,483,647 (the largest 32-bit signed integer)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Fix a, check the restO(√c)
  2. Two pointersO(√c)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for c near 2,147,483,647Verdict
Fix a, check the restO(√c)
Passes; one sqrt per step
Two pointersO(√c)
Best; only adds and compares

c = the input number; √c is at most about 46,341.

Edge cases to test

  • c = 0. 0² + 0² works, so the answer is true.
  • A perfect square. c = 49 is 0² + 7²: zero counts as one of the squares.
  • Twice a square. c = 18 is 3² + 3²: a and b may be the same number.
  • The largest input. c = 2,147,483,647 is false, and a² + b² overflows 32 bits on the way there.
  • Near the limit, true. c = 2,147,395,600 = 46,340² + 0² needs b to start exactly at √c.

Common mistakes

  • Starting a at 1 instead of 0, which misses perfect squares like 49.
  • Computing a² + b² in 32-bit integers, which overflows for c near 2³¹.
  • Trusting a floating-point square root without checking it, so b can be off by one.

How to talk through it

  1. 1Clarify. Can a or b be zero? Can they be equal? How large can c be?
  2. 2Give the brute force. Every pair up to √c is about 2 billion pairs; say that is too slow.
  3. 3Fix one side. For each a, b² must equal c − a²; check it with an integer square root.
  4. 4Code two pointers. a from 0, b from √c: too small moves a up, too big moves b down, using 64-bit sums.
  5. 5Test out loud. Run 0, a perfect square, 18, and the largest c before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?