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 integerx. If no such integer exists, return -1. It is guaranteed that there will be at most one pivot index for the given input.

Examples

Example 1

1
2
3
Input: n = 8
Output: 6
Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21.

Example 2

1
2
3
Input: n = 1
Output: 1
Explanation: 1 is the pivot integer since: 1 = 1.

Example 3

1
2
3
Input: n = 4
Output: -1
Explanation: It can be proved that no such integer exist.

Constraints

  • 1 <= n <= 1000

Solution

Method 1 – Math and Prefix Sum Formula

Intuition

The sum from 1 to x is x * (x + 1) / 2. The sum from x to n is n * (n + 1) / 2 - (x - 1) * x / 2. Set these equal and solve for x. This leads to a quadratic equation, and the solution must be an integer.

Approach

  1. Compute total = n * (n + 1) / 2.
  2. For x from 1 to n:
    • Compute left = x * (x + 1) / 2.
    • If left == total - (x - 1) * x / 2, return x.
  3. Alternatively, solve x^2 = total, so x = sqrt(total). If x is integer and x * x == total, return x.
  4. If no such x, return -1.

Code

1
2
3
4
5
6
7
8
class Solution {
public:
    int pivotInteger(int n) {
        int total = n * (n + 1) / 2;
        int x = sqrt(total);
        return x * x == total ? x : -1;
    }
};
1
2
3
4
5
6
7
8
func pivotInteger(n int) int {
    total := n * (n + 1) / 2
    x := int(math.Sqrt(float64(total)))
    if x*x == total {
        return x
    }
    return -1
}
1
2
3
4
5
6
7
class Solution {
    public int pivotInteger(int n) {
        int total = n * (n + 1) / 2;
        int x = (int)Math.sqrt(total);
        return x * x == total ? x : -1;
    }
}
1
2
3
4
5
6
7
class Solution {
    fun pivotInteger(n: Int): Int {
        val total = n * (n + 1) / 2
        val x = kotlin.math.sqrt(total.toDouble()).toInt()
        return if (x * x == total) x else -1
    }
}
1
2
3
4
5
class Solution:
    def pivotInteger(self, n: int) -> int:
        total = n * (n + 1) // 2
        x = int(total ** 0.5)
        return x if x * x == total else -1
1
2
3
4
5
6
7
impl Solution {
    pub fn pivot_integer(n: i32) -> i32 {
        let total = n * (n + 1) / 2;
        let x = (total as f64).sqrt() as i32;
        if x * x == total { x } else { -1 }
    }
}
1
2
3
4
5
6
7
class Solution {
    pivotInteger(n: number): number {
        const total = n * (n + 1) / 2;
        const x = Math.floor(Math.sqrt(total));
        return x * x === total ? x : -1;
    }
}

Complexity

  • ⏰ Time complexity: O(1) — Only a few arithmetic operations.
  • 🧺 Space complexity: O(1) — No extra space used.