Instead of looking for both numbers and from 0 to c with a double for loop, we can save a lot of repeated calculations by using a two-pointer strategy.
Since our required expression is a^2 + b^2 = c
, we know that the maximum value either a or b can have is sqrt(c)
, because if any one (or both) exceeds sqrt(c)
, the sum of both the squares of a and b would exceed c.
Code:
Python3
Big O Analysis
-
Runtime
The runtime complexity here is since our sample space to look for would be
a - b
wereb = sqrt(c)
-
Memory
The memory usage is since we are not using any extra data structure.
— A