Sum of Square Numbers - Problem

Given a non-negative integer c, determine whether there exist two integers a and b such that a² + b² = c.

Return true if such integers exist, otherwise return false.

Note: Both a and b can be zero or negative, but for this problem we only consider non-negative values where a ≥ 0 and b ≥ 0.

Input & Output

Example 1 — Basic True Case
$ Input: c = 5
Output: true
💡 Note: 1² + 2² = 1 + 4 = 5, so there exist integers a=1 and b=2 such that a² + b² = c
Example 2 — Perfect Square
$ Input: c = 4
Output: true
💡 Note: 0² + 2² = 0 + 4 = 4 (or 2² + 0² = 4), so it can be expressed as sum of two squares
Example 3 — Impossible Case
$ Input: c = 3
Output: false
💡 Note: No combination of two squares equals 3: 0²+0²=0, 0²+1²=1, 1²+1²=2, 0²+2²=4. None equal 3.

Constraints

  • 0 ≤ c ≤ 2³¹ - 1

Visualization

Tap to expand
Sum of Square Numbers INPUT c = 5 non-negative integer Find a, b where: a² + b² = c Constraints: a >= 0, b >= 0 0 <= c <= 2³¹ - 1 Search range: 0 to sqrt(5) a, b in [0, 1, 2] ALGORITHM STEPS 1 Two Pointers Setup a = 0, b = sqrt(c) = 2 2 Calculate Sum sum = a² + b² 3 Compare & Adjust sum > c: b-- | sum < c: a++ 4 Check Result sum == c: return true Iteration Trace (c=5) a b a²+b² Action 0 2 4 a++ 1 2 5 FOUND! 1² + 2² = 1 + 4 = 5 [OK] FINAL RESULT true Solution exists! Solution Found: a = 1, b = 2 1² + 2² = 5 Visual: Squares summing to 5 1 + 4 = 5 Time: O(sqrt(c)) | Space: O(1) Key Insight: Two-pointer technique works because a² + b² is monotonic: increasing 'a' increases the sum, decreasing 'b' decreases it. Start with a=0, b=sqrt(c) and converge towards the solution in O(sqrt(c)) time. TutorialsPoint - Sum of Square Numbers | Two Pointers Optimal Approach
Asked in
Facebook 25 Google 20 Microsoft 15
42.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen