101 Logo
onenoughtone

Code Implementation

Square Number Decomposition Implementation

Below is the implementation of the square number decomposition:

solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Two Pointers Approach
* Time Complexity: O(√c) - We iterate through at most √c pairs of numbers
* Space Complexity: O(1) - We only use a constant amount of space
*
* @param {number} c - The target number
* @return {boolean} - Whether c can be expressed as the sum of two squares
*/
function judgeSquareSum(c) {
let a = 0;
let b = Math.floor(Math.sqrt(c));
while (a <= b) {
const sum = a * a + b * b;
if (sum === c) {
return true;
} else if (sum < c) {
a++;
} else {
b--;
}
}
return false;
}

Step-by-Step Explanation

Let's break down the implementation:

  1. 1. Understand the Problem: First, understand that we need to determine if a given non-negative integer c can be expressed as the sum of two perfect squares.
  2. 2. Set Up Two Pointers: Initialize two pointers: a starting from 0 and b starting from the square root of c.
  3. 3. Implement the Two-Pointer Approach: Use a while loop to iterate while a ≤ b, calculating the sum of squares at each step and adjusting the pointers accordingly.
  4. 4. Check for a Solution: If the sum of squares equals c, return true. If it's less than c, increment a. If it's greater than c, decrement b.
  5. 5. Handle Edge Cases: Consider edge cases such as c = 0 or c = 1, which have straightforward solutions.
  6. 6. Optimize for Large Inputs: Ensure that the solution works efficiently for large values of c by using appropriate data types and algorithms.
  7. 7. Test the Solution: Verify the solution with the provided examples and additional test cases.
ProblemSolutionCode
101 Logo
onenoughtone