LeetCode 2485: Find the Pivot Integer

MathPrefix Sum

Problem Description

Explanation

To find the pivot integer, we can iterate from 1 to n and calculate the sum of elements on both sides of the pivot candidate x. If the sums are equal, we return x as the pivot integer. If we finish the loop without finding a pivot, we return -1.

  • Algorithm:

    1. Initialize variables sumLeft and sumRight to keep track of the sums on the left and right sides of the pivot candidate.
    2. Iterate from 1 to n:
      • Update sumLeft by adding the current number.
      • Calculate sumRight as the total sum from 1 to n minus sumLeft.
      • If sumLeft equals sumRight, return the current number as the pivot integer.
    3. If no pivot integer is found, return -1.
  • Time Complexity: O(n) where n is the given positive integer.

  • Space Complexity: O(1)

Solutions

class Solution {
    public int findPivotInteger(int n) {
        int sumLeft = 0;
        int sumRight = 0;
        
        for (int x = 1; x <= n; x++) {
            sumLeft += x;
            sumRight = (n * (n + 1) / 2) - sumLeft;
            if (sumLeft == sumRight) {
                return x;
            }
        }
        
        return -1;
    }
}

Loading editor...