DSCPPAS278C - Editorial

Problem Statement:

Given a positive integer c, determine whether it can be expressed as the sum of two square numbers. In other words, you need to determine if there exist two non-negative integers a and b such that: c = a^2 + b^2

Approach:

This problem can be solved using a two-pointer technique. The idea is based on the observation that if c = a^2 + b^2, then a and b must satisfy the equation for some values between 0 and the square root of c.

Detailed Approach:

  1. Two-Pointer Technique:

    • Initialize two pointers:
      • left starts at 0 (corresponding to a).
      • right starts at sqrt(c) (corresponding to b).
    • The goal is to find if there exists a pair (a, b) such that a^2 + b^2 = c.
  2. Iterative Search:

    • Calculate the sum sum = left^2 + right^2.
    • Compare sum with c:
      • If sum == c, return true because we have found the values a and b.
      • If sum < c, increment the left pointer to increase the sum.
      • If sum > c, decrement the right pointer to decrease the sum.
    • Continue this process until left exceeds right.
  3. Return Result:

    • If no such pair is found by the time left exceeds right, return false.

Complexity:

  • Time Complexity: The time complexity of this solution is O(sqrt(c)). This is because the maximum number of iterations is determined by the value of sqrt(c), as both pointers move towards each other.
  • Space Complexity: The space complexity is O(1), as the solution only uses a few extra variables for computation.
Note:

There are other approaches too to solve this problem. Can you think think of any?