Advertisement

Sum of Square Numbers - LeetCode 633 Solution

Sum of Square Numbers - Complete Solution Guide

Sum of Square Numbers is LeetCode problem 633, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given a non-negative integer c , decide whether there're two integers a and b such that a 2 + b 2 = c . Example 1: Input: c = 5 Output: true Explanation: 1 * 1 + 2 * 2 = 5 Example 2: Input: c = 3 Output: false Constraints: 0 <= c <= 2 31 - 1

Detailed Explanation

The problem asks us to determine if a given non-negative integer 'c' can be expressed as the sum of squares of two integers, 'a' and 'b'. In other words, we need to check if there exist integers 'a' and 'b' such that a<sup>2</sup> + b<sup>2</sup> = c. The input is a single integer 'c', and the output should be a boolean value: 'true' if such 'a' and 'b' exist, and 'false' otherwise. The constraint is that 0 <= c <= 2<sup>31</sup> - 1.

Solution Approach

The solution utilizes a two-pointer approach. One pointer, 'left', starts at 0, and the other pointer, 'right', starts at the square root of 'c'. We then iterate while 'left' is less than or equal to 'right'. In each iteration, we calculate the sum of squares of 'left' and 'right'. If the sum is equal to 'c', we return 'true'. If the sum is less than 'c', we increment 'left' to increase the sum. If the sum is greater than 'c', we decrement 'right' to decrease the sum. If the loop completes without finding a solution, we return 'false'.

Step-by-Step Algorithm

  1. Step 1: Initialize two pointers, 'left' to 0 and 'right' to the integer square root of 'c'.
  2. Step 2: Start a while loop that continues as long as 'left' is less than or equal to 'right'.
  3. Step 3: Inside the loop, calculate the sum of squares: 'current_sum' = left * left + right * right.
  4. Step 4: Compare 'current_sum' with 'c':
  5. Step 5: If 'current_sum' == 'c', return 'true' because we found a solution.
  6. Step 6: If 'current_sum' < 'c', increment 'left' to try a larger value for 'a'.
  7. Step 7: If 'current_sum' > 'c', decrement 'right' to try a smaller value for 'b'.
  8. Step 8: If the loop finishes without finding a solution (i.e., 'left' becomes greater than 'right'), return 'false'.

Key Insights

  • Insight 1: The problem can be solved efficiently using a two-pointer approach, similar to the two-sum problem when dealing with a sorted array.
  • Insight 2: The range of possible values for 'a' and 'b' is limited by the square root of 'c'. We can use this to constrain the search space and optimize the solution.
  • Insight 3: The problem can be also solved using Binary Search algorithm.

Complexity Analysis

Time Complexity: O(sqrt(c))

Space Complexity: O(1)

Topics

This problem involves: Math, Two Pointers, Binary Search.

Companies

Asked at: LinkedIn, Two Sigma.