Problem
Given a non-negative integer c
, decide whether there’re two integers a
and b
such that a^2 + b^2 = c
.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
There are some gotchas to look out for when checking for a
and b
:
0
is also valid integer, and- these two numbers can be the same…
Here is the video explanation:
Method 1 - Brute Force
Run two nested loops - 1 for a
and another b
till √n
, see if they add up to c
. This takes O(√n^2) = O(n)
time.
Method 2 - Using Hashset
Code
|
|
Complexity
- ⏰ Time complexity:
O(√n)
- 🧺 Space complexity:
O(√n)
Method 3 - Loop till sqrt n and find b
Code
|
|
Complexity
- ⏰ Time complexity:
O(√n)
- 🧺 Space complexity:
O(1)
Method 4 - Two pointer approach
We can start with a = left = 0
, and b = right = √c
. Now, we find c
such that c = left^2 + right^2
. Note that c = left ^2 + right ^ 2
can overflow.
Code
|
|
Complexity
- ⏰ Time complexity:
O(√n)
- 🧺 Space complexity:
O(1)