Find the Pivot Integer — LeetCode 2485 Python Solution

EasyMathPrefix Sum
Problem
#2485
Pattern
Prefix Sum
Reading time
2 min

The 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 integer x.

Example

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

Python solution

Python
class Solution:
    def pivotInteger(self, n: int) -> int:
        for x in range(1, n + 1):
            if (1 + x) * x == (x + n) * (n - x + 1):
                return x
        return -1

Complexity

MeasureComplexity
TimeO(n), where n is the given positive integer n
SpaceO(1) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2485. Find the Pivot Integer is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2485. Find the Pivot Integer?
LeetCode 2485. Find the Pivot Integer is rated Easy on LeetCode.
What is the time complexity of LeetCode 2485. Find the Pivot Integer?
The Python solution on this page runs in O(n), where n is the given positive integer n.
What is the space complexity of LeetCode 2485. Find the Pivot Integer?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2485. Find the Pivot Integer cover?
LeetCode 2485. Find the Pivot Integer is tagged Math and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview