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 INPUT Numbers from 1 to n 1 2 3 4 5 6 7 8 Input: n = 8 Find x where: sum(1...x) = sum(x...n) Left Sum 1+2+...+x Right Sum x+...+n ALGORITHM STEPS 1 Calculate Total Sum total = n*(n+1)/2 = 8*9/2 = 36 2 Math Derivation x*(x+1)/2 = total - x*(x-1)/2 Simplify: x^2 = total 3 Find x = sqrt(total) x = sqrt(36) = 6 6 is a perfect square root 4 Verify Solution Left: 1+2+3+4+5+6 = 21 Right: 6+7+8 = 21 21 == 21 [OK] Complexity Time: O(1) | Space: O(1) FINAL RESULT Pivot divides sequence equally Left Side 1+2+3+4+5+6 = 21 Right Side 6+7+8 = 21 = PIVOT x = 6 1 2 3 4 5 6 PIVOT 7 8 Output 6 Key Insight: The pivot x exists only when the total sum n*(n+1)/2 is a perfect square. If sqrt(total) is an integer and falls within [1, n], that's our pivot. Otherwise, return -1. Formula: x = sqrt(n * (n + 1) / 2) -- Check if x * x equals total sum TutorialsPoint - Find the Pivot Integer | Optimal Solution O(1)
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