#2485
Find the Pivot Integer
EasyMathPrefix SumMathematical SummationPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of calculating sums repeatedly, we can derive the pivot condition using a mathematical formula, which allows us to find the pivot in linear time.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the total sum of integers from 1 to n using the formula n * (n + 1) / 2.
- 2Step 2: Iterate through each integer x from 1 to n.
- 3Step 3: For each x, check if 2 * sum(1 to x) == total_sum. If true, return x.
- 4Step 4: If no pivot is found after checking all integers, return -1.
solution.py10 lines
1# Full working Python code
2
3def find_pivot_integer(n):
4 total_sum = n * (n + 1) // 2
5 sum_left = 0
6 for x in range(1, n + 1):
7 sum_left += x
8 if 2 * sum_left == total_sum:
9 return x
10 return -1ℹ
Complexity note: The time complexity is O(n) because we only loop through the integers once, and the space complexity is O(1) since we use a constant amount of space.
- 1Using mathematical properties can significantly reduce the time complexity.
- 2Understanding the relationship between the sums can lead to a more efficient solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.