Leetcode 2485. Find the Pivot Integer
You are given a positive integer n
. The task is to find a pivot integer x
that satisfies the following condition: the sum of all integers from 1
to x
is equal to the sum of all integers from x
to n
. If no such x
exists, return -1
. If multiple such x
exist, you can return any of them.
n
be very large or is there a constraint on the size of n
?
Typically, we might assume n
is within a practical range suitable for medium complexity algorithms, but specific constraints were not provided.n = 1
?
Given n
is a positive integer, it’s good to consider all edge cases including the smallest valid n
.1
to x
can be expressed using the formula for the sum of an arithmetic series: S1 = x * (x + 1) / 2
.x
to n
can also be expressed, but this is from x+1
to n
plus x
: S2 = x + (n * (n + 1) / 2 - x * (x - 1) / 2)
.x
in the range 1
to n
, we return x
. Otherwise, we return -1
.public class Solution {
public int pivotInteger(int n) {
// total sum of all numbers from 1 to n
int totalSum = (n * (n + 1)) / 2;
// sum from 1 to x should be equal to sum from x to n
int currentSum = 0;
for (int x = 1; x <= n; x++) {
currentSum += x;
if (currentSum == totalSum - currentSum + x) {
return x;
}
}
return -1; // if no pivot found
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.pivotInteger(8)); // Output will be an integer that satisfies the condition, or -1 if none exists
}
}
The time complexity of this solution is O(n)
due to the single loop iterating through all integers from 1
to n
. This is efficient given that we are comparing sums within this bounded input range.
1
to n
.1
to n
and calculate the running sum (currentSum
).x
, we check if currentSum
equals the remaining sum (totalSum - currentSum + x
).x
as the pivot integer.-1
.This solution correctly identifies the pivot integer or determines that none exists in linear time, ensuring efficient processing for typical input sizes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?