Find the Pivot Integer - Problem
Given a positive integer n, find the pivot integer x such that:
- The sum of all elements between
1andxinclusively equals the sum of all elements betweenxandninclusively.
Return the pivot integer x. If no such integer exists, return -1.
Note: It is guaranteed that there will be at most one pivot index for the given input.
Input & Output
Example 1 — Basic Case
$
Input:
n = 8
›
Output:
6
💡 Note:
The pivot integer is 6. Sum from 1 to 6: 1+2+3+4+5+6 = 21. Sum from 6 to 8: 6+7+8 = 21. Both sums equal 21.
Example 2 — Single Element
$
Input:
n = 1
›
Output:
1
💡 Note:
The pivot integer is 1. Sum from 1 to 1: 1. Sum from 1 to 1: 1. Both sums equal 1.
Example 3 — No Pivot Exists
$
Input:
n = 4
›
Output:
-1
💡 Note:
No pivot exists. For any x: sum(1 to x) ≠ sum(x to 4). Total sum is 10, and √10 ≈ 3.16 is not an integer.
Constraints
- 1 ≤ n ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input
Given n=8, need to find pivot x
2
Balance Point
Find x where sum(1..x) = sum(x..n)
3
Output
Return pivot x=6 or -1 if none exists
Key Takeaway
🎯 Key Insight: The pivot condition algebraically simplifies to x² = total_sum, allowing O(1) solution
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code