Skip to main content
Back to problems
#2485
Easy Algorithms

Find the pivot integer

Math Prefix Sum
83.8% acceptance
Feb 25, 2026
1432
60
Given a positive integer n, find the pivot integer x such that: sum(1..=x) == sum(x..=n) Return x, or -1 if no such integer exists.

Solution

Rust
Time O(1)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn pivot_integer(n: i32) -> i32 {
    // x^2 = n*(n+1)/2
    let total = n * (n + 1) / 2;
    let x = (total as f64).sqrt() as i32;
    if x * x == total { x } else { -1 }
  }
}