Find the Pivot Integer Problem
#2485
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2485.
Given a positive integer n, find the pivot integer x such that:
- The sum of all elements between
1andxinclusively equals the sum of all elements betweenxandninclusively.
Return the pivot integer x. If no such integer exists, return -1. It is guaranteed that there will be at most one pivot index for the given input.
Example 1:
Input: n = 8
Output: 6
Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21.
Example 2:
Input: n = 1
Output: 1
Explanation: 1 is the pivot integer since: 1 = 1.
Example 3:
Input: n = 4
Output: -1
Explanation: It can be proved that no such integer exist.
Constraints:
1 <= n <= 1000
Solution
Approach: Enumeration
Try every x from 1 to n. The sum 1 + ... + x equals x(x + 1) / 2 and the sum x + ... + n equals (x + n)(n - x + 1) / 2, so x is the pivot when (1 + x) * x == (x + n) * (n - x + 1). Return the first such x, or -1 if there is none.
Complexity: O(n) time and O(1) space.
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