Find the Pivot Integer - Problem

Given a positive integer n, find the pivot integer x such that:

  • The sum of all elements between 1 and x inclusively equals the sum of all elements between x and n inclusively.

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
Find the Pivot Integer Problem (n=8)Range: 1 to 812345678Left sum: 1+2+3+4+5+6 = 21Right sum: 6+7+8 = 21Balance!Pivot: x = 6Mathematical insight:x² = total_sum = 36, so x = 6
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
Asked in
Microsoft 15 Amazon 12 Google 8
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen