You are given a positive integer n
. A pivot integer is an integer x
such that the sum of all integers from 1 to x
is equal to the sum of all integers from x
to n
. Return the pivot integer x
. If no such integer exists, return -1
. If there are multiple pivot integers, return the largest one.
n
?
n
? (E.g., small values below 100, or very large values up to 10^9)n
be 1?n
guaranteed to be a positive integer?n
is a positive integer.-1
.x
integers: ( \text{Sum}(1 \text{ to } x) = \frac{x \times (x + 1)}{2} )x
to n
:
[
\text{Sum}(x \text{ to } n) = \text{Sum}(1 \text{ to } n) - \text{Sum}(1 \text{ to } (x-1))
]
[
= \frac{n \times (n + 1)}{2} - \frac{(x-1) \times x}{2}
]x
:
[
\frac{x \times (x + 1)}{2} = \frac{n \times (n + 1)}{2} - \frac{(x-1) \times x}{2}
]x
.def find_pivot_integer(n: int) -> int:
left_sum = 0
total_sum = n * (n + 1) // 2
for x in range(1, n + 1):
left_sum += x
right_sum = total_sum - left_sum + x
if left_sum == right_sum:
return x
return -1
# Test the function with an example
print(find_pivot_integer(8)) # Example test case
n
.x
from 1 to n
:
x
as the pivot integer.-1
.The time complexity of this solution is (O(n)) because it involves iterating through the integers from 1 to n
. The space complexity is (O(1)) because the space required does not depend on the input size and only a few variables are used.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?