Find the Pivot Integer

easy math prefix sum

Problem

Given a positive integer n, find the pivot integer x such that the sum of all integers from 1 to x (inclusive) equals the sum of all integers from x to n (inclusive). Return that pivot x, or -1 if none exists. There is at most one valid pivot.

Inputn = 8
Output6
1 + 2 + 3 + 4 + 5 + 6 = 21 and 6 + 7 + 8 = 21, so 6 is the pivot.

def pivotInteger(n):
    total = n * (n + 1) // 2     # sum of 1..n
    left = 0                     # running prefix sum 1..x
    for x in range(1, n + 1):
        left += x                # extend prefix to include x
        # right side is sum of x..n = total - (left - x)
        right = total - left + x
        if left == right:        # both halves balance at x
            return x
    return -1                    # no pivot exists
function pivotInteger(n) {
  const total = (n * (n + 1)) / 2;   // sum of 1..n
  let left = 0;                       // running prefix sum 1..x
  for (let x = 1; x <= n; x++) {
    left += x;                        // extend prefix to include x
    // right side is sum of x..n = total - (left - x)
    const right = total - left + x;
    if (left === right) {             // both halves balance at x
      return x;
    }
  }
  return -1;                          // no pivot exists
}
int pivotInteger(int n) {
    int total = n * (n + 1) / 2;   // sum of 1..n
    int left = 0;                  // running prefix sum 1..x
    for (int x = 1; x <= n; x++) {
        left += x;                 // extend prefix to include x
        // right side is sum of x..n = total - (left - x)
        int right = total - left + x;
        if (left == right) {       // both halves balance at x
            return x;
        }
    }
    return -1;                     // no pivot exists
}
int pivotInteger(int n) {
    int total = n * (n + 1) / 2;   // sum of 1..n
    int left = 0;                  // running prefix sum 1..x
    for (int x = 1; x <= n; x++) {
        left += x;                 // extend prefix to include x
        // right side is sum of x..n = total - (left - x)
        int right = total - left + x;
        if (left == right) {       // both halves balance at x
            return x;
        }
    }
    return -1;                     // no pivot exists
}
Time: O(n) Space: O(1)