Given a positive integer n, find the pivot integer x such that:
1 and x inclusively equals the sum of all elements between x and n inclusively.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 <= 1000This approach involves iterating through each number from 1 to n and checking if it satisfies the given condition of a pivot integer. For each candidate pivot integer x, calculate the sum of numbers from 1 to x using the formula for the sum of an arithmetic series. Similarly, calculate the sum from x to n. Compare these sums to determine if x is a pivot integer.
The function find_pivot iterates through numbers from 1 to n. For each number, it calculates the sum of numbers from 1 to x (sum1) and from x to n (sum2). It returns x if the two sums are equal, otherwise returns -1 at the end.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n).
Space Complexity: O(1).
Instead of iterating through each possible x, we can use mathematical formulation. As the sum from 1 to n is fixed, let's denote the total sum as S. Then, for pivot x, the condition becomes:
(x * (x + 1)) / 2 = (S - ((x - 1) * x) / 2)
From this, derive a formula to find x directly if it exists. Solving algebraically can help us identify the pivot integer without iteration.
This optimized solution uses algebra to directly verify if a number x is a pivot without recalculating sums within the loop.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n).
Space Complexity: O(1).
| Approach | Complexity |
|---|---|
| Brute Force Search | Time Complexity: O(n). |
| Optimized Arithmetic Approach | Time Complexity: O(n). |
Find Pivot Index - Leetcode 724 - Python • NeetCode • 63,567 views views
Watch 9 more video solutions →Practice Find the Pivot Integer with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor