LeetCode 2485: Find the Pivot Integer
Problem Description
Explanation
To find the pivot integer, we can iterate from 1 to n and calculate the sum of elements on both sides of the pivot candidate x. If the sums are equal, we return x as the pivot integer. If we finish the loop without finding a pivot, we return -1.
-
Algorithm:
- Initialize variables
sumLeft
andsumRight
to keep track of the sums on the left and right sides of the pivot candidate. - Iterate from 1 to n:
- Update
sumLeft
by adding the current number. - Calculate
sumRight
as the total sum from 1 to n minussumLeft
. - If
sumLeft
equalssumRight
, return the current number as the pivot integer.
- Update
- If no pivot integer is found, return -1.
- Initialize variables
-
Time Complexity: O(n) where n is the given positive integer.
-
Space Complexity: O(1)
Solutions
class Solution {
public int findPivotInteger(int n) {
int sumLeft = 0;
int sumRight = 0;
for (int x = 1; x <= n; x++) {
sumLeft += x;
sumRight = (n * (n + 1) / 2) - sumLeft;
if (sumLeft == sumRight) {
return x;
}
}
return -1;
}
}
Loading editor...