Facebook Pixel

2485. Find the Pivot Integer

Problem Description

You are given a positive integer n. Your task is to find a special number called the pivot integer x that satisfies a specific condition.

The condition is that the sum of all integers from 1 to x (including both 1 and x) must equal the sum of all integers from x to n (including both x and n).

For example, if n = 8 and x = 6:

  • The sum from 1 to 6 is: 1 + 2 + 3 + 4 + 5 + 6 = 21
  • The sum from 6 to 8 is: 6 + 7 + 8 = 21

Since both sums are equal, 6 would be the pivot integer.

The problem guarantees that there will be at most one pivot integer for any given input. If a pivot integer exists, return it. If no such integer exists, return -1.

The solution checks each possible value of x from 1 to n and uses the formula for the sum of consecutive integers. The equation (1 + x) * x = (x + n) * (n - x + 1) compares:

  • Left side: twice the sum from 1 to x (using the formula sum = (first + last) * count / 2)
  • Right side: twice the sum from x to n

When these are equal, we've found our pivot integer.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight is recognizing that we need to find a point where two sums are equal. Since we're dealing with consecutive integers, we can leverage the arithmetic series sum formula to avoid actually computing the sums repeatedly.

For any range of consecutive integers from a to b, the sum equals (first + last) * count / 2. This gives us:

  • Sum from 1 to x: (1 + x) * x / 2
  • Sum from x to n: (x + n) * (n - x + 1) / 2

Notice that x appears in both sums since it's included in both ranges. This is intentional based on the problem definition.

Setting these two sums equal: (1 + x) * x / 2 = (x + n) * (n - x + 1) / 2

We can multiply both sides by 2 to eliminate the fraction: (1 + x) * x = (x + n) * (n - x + 1)

This gives us a clean equation to check for each possible value of x.

The brute force approach of checking every value from 1 to n is actually quite efficient here since:

  1. We have a limited search space (only n values to check)
  2. Each check is O(1) using our formula
  3. The problem guarantees at most one solution, so we can return immediately when found

The mathematical relationship could potentially be solved algebraically to find x directly, but the enumeration approach is straightforward and runs in O(n) time, which is acceptable for this problem's constraints.

Learn more about Math and Prefix Sum patterns.

Solution Approach

The solution uses a direct enumeration approach to find the pivot integer. Here's how the implementation works:

Algorithm: Linear Search with Mathematical Validation

We iterate through each possible value of x from 1 to n and check if it satisfies our pivot condition using the derived equation:

for x in range(1, n + 1):
    if (1 + x) * x == (x + n) * (n - x + 1):
        return x

Step-by-step breakdown:

  1. Iteration Range: We check every integer from 1 to n inclusive as a potential pivot

    • range(1, n + 1) generates values [1, 2, 3, ..., n]
  2. Condition Check: For each x, we verify if:

    • (1 + x) * x == (x + n) * (n - x + 1)
    • Left side (1 + x) * x represents twice the sum from 1 to x
    • Right side (x + n) * (n - x + 1) represents twice the sum from x to n
    • The factor of 2 is implicit on both sides, so we can compare directly
  3. Early Return: As soon as we find a value that satisfies the equation, we return it

    • This is valid because the problem guarantees at most one pivot exists
  4. Default Case: If no value in the range satisfies the condition, we return -1

Time Complexity: O(n) - We potentially check all n values, with each check taking O(1) time

Space Complexity: O(1) - We only use a single variable x for iteration and perform constant-time arithmetic operations

The elegance of this solution lies in transforming the sum comparison problem into a simple arithmetic equation check, avoiding the need to actually compute cumulative sums.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through finding the pivot integer for n = 8.

We need to find an x where the sum from 1 to x equals the sum from x to 8.

Step 1: Check x = 1

  • Equation: (1 + 1) * 1 == (1 + 8) * (8 - 1 + 1)
  • Simplify: 2 * 1 == 9 * 8
  • Result: 2 == 72 ❌ Not equal, continue

Step 2: Check x = 2

  • Equation: (1 + 2) * 2 == (2 + 8) * (8 - 2 + 1)
  • Simplify: 3 * 2 == 10 * 7
  • Result: 6 == 70 ❌ Not equal, continue

Step 3: Check x = 3

  • Equation: (1 + 3) * 3 == (3 + 8) * (8 - 3 + 1)
  • Simplify: 4 * 3 == 11 * 6
  • Result: 12 == 66 ❌ Not equal, continue

Step 4: Check x = 4

  • Equation: (1 + 4) * 4 == (4 + 8) * (8 - 4 + 1)
  • Simplify: 5 * 4 == 12 * 5
  • Result: 20 == 60 ❌ Not equal, continue

Step 5: Check x = 5

  • Equation: (1 + 5) * 5 == (5 + 8) * (8 - 5 + 1)
  • Simplify: 6 * 5 == 13 * 4
  • Result: 30 == 52 ❌ Not equal, continue

Step 6: Check x = 6

  • Equation: (1 + 6) * 6 == (6 + 8) * (8 - 6 + 1)
  • Simplify: 7 * 6 == 14 * 3
  • Result: 42 == 42 ✅ Equal! Found our pivot

Verification:

  • 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, confirming x = 6 is the pivot integer

The algorithm returns 6 immediately upon finding this match.

Solution Implementation

1class Solution:
2    def pivotInteger(self, n: int) -> int:
3        """
4        Find the pivot integer x where sum(1 to x) equals sum(x to n).
5      
6        Args:
7            n: The upper bound of the range [1, n]
8          
9        Returns:
10            The pivot integer if it exists, otherwise -1
11        """
12        # Iterate through all possible pivot values from 1 to n
13        for x in range(1, n + 1):
14            # Check if sum from 1 to x equals sum from x to n
15            # Left sum: 1 + 2 + ... + x = (1 + x) * x / 2
16            # Right sum: x + (x+1) + ... + n = (x + n) * (n - x + 1) / 2
17            # We can omit division by 2 on both sides for comparison
18            if (1 + x) * x == (x + n) * (n - x + 1):
19                return x
20      
21        # No pivot found in the range
22        return -1
23
1class Solution {
2    /**
3     * Find the pivot integer x such that the sum of all integers from 1 to x
4     * equals the sum of all integers from x to n.
5     * 
6     * @param n The upper bound of the range [1, n]
7     * @return The pivot integer if it exists, otherwise -1
8     */
9    public int pivotInteger(int n) {
10        // Iterate through all possible pivot values from 1 to n
11        for (int pivotCandidate = 1; pivotCandidate <= n; ++pivotCandidate) {
12            // Calculate sum from 1 to pivotCandidate using formula: sum = (first + last) * count / 2
13            // Left sum: 1 + 2 + ... + pivotCandidate = (1 + pivotCandidate) * pivotCandidate / 2
14            int leftSum = (1 + pivotCandidate) * pivotCandidate / 2;
15          
16            // Calculate sum from pivotCandidate to n
17            // Right sum: pivotCandidate + (pivotCandidate+1) + ... + n
18            // Count of elements: (n - pivotCandidate + 1)
19            // Sum = (first + last) * count / 2 = (pivotCandidate + n) * (n - pivotCandidate + 1) / 2
20            int rightSum = (pivotCandidate + n) * (n - pivotCandidate + 1) / 2;
21          
22            // Check if left sum equals right sum
23            if (leftSum == rightSum) {
24                return pivotCandidate;
25            }
26        }
27      
28        // No valid pivot found
29        return -1;
30    }
31}
32
1class Solution {
2public:
3    int pivotInteger(int n) {
4        // Iterate through all possible pivot candidates from 1 to n
5        for (int pivot = 1; pivot <= n; ++pivot) {
6            // Calculate sum from 1 to pivot: sum = (first + last) * count / 2
7            // Left sum: 1 + 2 + ... + pivot = (1 + pivot) * pivot / 2
8            int leftSum = (1 + pivot) * pivot / 2;
9          
10            // Calculate sum from pivot to n: sum = (first + last) * count / 2
11            // Right sum: pivot + (pivot+1) + ... + n = (pivot + n) * (n - pivot + 1) / 2
12            int rightSum = (pivot + n) * (n - pivot + 1) / 2;
13          
14            // Check if left sum equals right sum
15            if (leftSum == rightSum) {
16                return pivot;
17            }
18        }
19      
20        // No valid pivot found
21        return -1;
22    }
23};
24
1/**
2 * Finds the pivot integer x such that the sum of all elements from 1 to x
3 * equals the sum of all elements from x to n
4 * 
5 * The mathematical formula used:
6 * - Sum from 1 to x: (1 + x) * x / 2
7 * - Sum from x to n: (x + n) * (n - x + 1) / 2
8 * - For pivot: 2 * sum(1 to x) = 2 * sum(x to n), so we compare without dividing by 2
9 * 
10 * @param n - The upper bound of the range [1, n]
11 * @returns The pivot integer if it exists, otherwise -1
12 */
13function pivotInteger(n: number): number {
14    // Iterate through all possible pivot values from 1 to n
15    for (let pivotCandidate = 1; pivotCandidate <= n; ++pivotCandidate) {
16        // Calculate sum from 1 to pivotCandidate (inclusive)
17        const leftSum = (1 + pivotCandidate) * pivotCandidate;
18      
19        // Calculate sum from pivotCandidate to n (inclusive)
20        const rightSum = (pivotCandidate + n) * (n - pivotCandidate + 1);
21      
22        // Check if the sums are equal (pivot found)
23        if (leftSum === rightSum) {
24            return pivotCandidate;
25        }
26    }
27  
28    // No pivot integer found in the range
29    return -1;
30}
31

Time and Space Complexity

The time complexity is O(n), where n is the given positive integer. The algorithm uses a linear search approach, iterating through all integers from 1 to n in the worst case. For each value of x, it performs a constant-time arithmetic comparison (1 + x) * x == (x + n) * (n - x + 1). Since the loop runs at most n times and each iteration takes O(1) time, the overall time complexity is O(n).

The space complexity is O(1). The algorithm only uses a fixed amount of extra space for the loop variable x and temporary values during the arithmetic calculations. No additional data structures are created that grow with the input size, making the space usage constant.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Integer Overflow in Large Values

When n is large, the multiplication operations (1 + x) * x and (x + n) * (n - x + 1) can potentially cause integer overflow in languages with fixed integer sizes. Although Python handles arbitrary precision integers automatically, this could be problematic in other languages like C++ or Java.

Solution: Use a mathematical approach with square root to avoid large multiplications:

def pivotInteger(self, n: int) -> int:
    total_sum = n * (n + 1) // 2
    pivot_squared = total_sum
    pivot = int(pivot_squared ** 0.5)
  
    # Check if pivot is valid (perfect square and in range)
    if pivot * pivot == pivot_squared and 1 <= pivot <= n:
        return pivot
    return -1

2. Off-by-One Errors in Formula Derivation

A common mistake is incorrectly deriving the equation by forgetting that x appears in both sums. Some might write:

  • Wrong: sum(1 to x-1) == sum(x+1 to n)
  • Wrong: (1 + x-1) * (x-1) == (x+1 + n) * (n - x)

Solution: Remember that x is included in BOTH sums. The correct comparison is:

  • Sum from 1 to x (inclusive) == Sum from x to n (inclusive)

3. Inefficient Sum Calculation

Some might implement the solution by actually calculating the sums in each iteration:

# Inefficient approach - O(n²) time complexity
for x in range(1, n + 1):
    left_sum = sum(range(1, x + 1))
    right_sum = sum(range(x, n + 1))
    if left_sum == right_sum:
        return x

Solution: Always use the arithmetic series formula instead of computing sums iteratively. The formula sum = (first + last) * count / 2 reduces each check to O(1).

4. Assuming Multiple Pivots Exist

Some solutions might continue searching after finding a pivot or try to collect all pivots, not realizing the problem guarantees at most one pivot exists.

Solution: Return immediately upon finding the first valid pivot, as there can be at most one for any given n.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

What does the following code do?

1def f(arr1, arr2):
2  i, j = 0, 0
3  new_arr = []
4  while i < len(arr1) and j < len(arr2):
5      if arr1[i] < arr2[j]:
6          new_arr.append(arr1[i])
7          i += 1
8      else:
9          new_arr.append(arr2[j])
10          j += 1
11  new_arr.extend(arr1[i:])
12  new_arr.extend(arr2[j:])
13  return new_arr
14
1public static List<Integer> f(int[] arr1, int[] arr2) {
2  int i = 0, j = 0;
3  List<Integer> newArr = new ArrayList<>();
4
5  while (i < arr1.length && j < arr2.length) {
6      if (arr1[i] < arr2[j]) {
7          newArr.add(arr1[i]);
8          i++;
9      } else {
10          newArr.add(arr2[j]);
11          j++;
12      }
13  }
14
15  while (i < arr1.length) {
16      newArr.add(arr1[i]);
17      i++;
18  }
19
20  while (j < arr2.length) {
21      newArr.add(arr2[j]);
22      j++;
23  }
24
25  return newArr;
26}
27
1function f(arr1, arr2) {
2  let i = 0, j = 0;
3  let newArr = [];
4  
5  while (i < arr1.length && j < arr2.length) {
6      if (arr1[i] < arr2[j]) {
7          newArr.push(arr1[i]);
8          i++;
9      } else {
10          newArr.push(arr2[j]);
11          j++;
12      }
13  }
14  
15  while (i < arr1.length) {
16      newArr.push(arr1[i]);
17      i++;
18  }
19  
20  while (j < arr2.length) {
21      newArr.push(arr2[j]);
22      j++;
23  }
24  
25  return newArr;
26}
27

Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More