Problem Description
Given a positive integer n, find the pivot integer x such that the sum of the numbers from 1 to x is equal to the sum from x to n. If such an integer exists, return x; otherwise, return -1.
Key Insights
- The sum from 1 to x can be computed using the formula: x * (x + 1) / 2.
- The sum from x to n can be computed by taking the total sum from 1 to n and subtracting the sum from 1 to (x-1).
- Setting these two sums equal leads to an equation that simplifies to: 2 * x^2 = n * (n + 1).
- Thus, we need to check if n * (n + 1) / 2 is a perfect square, and if so, the square root of that value is the pivot integer.
Space and Time Complexity
Time Complexity: O(1) Space Complexity: O(1)
Solution
We start by computing the total sum from 1 to n using the formula n * (n + 1) / 2. Using the derived relationship, the pivot integer x must satisfy x^2 = n * (n + 1) / 2. We calculate x as the square root of n * (n + 1) / 2. If x is an integer (i.e., x^2 equals n*(n+1)/2), we return x; otherwise, we return -1. This solution uses basic arithmetic operations and a square root function, resulting in constant time and space complexity.