Find the Pivot Integer - LeetCode Daily Challenge
Problem Statement
Given a positive integer n
, find the pivot integer x
such that:
- The sum of all elements between
1
andx
inclusively equals the sum of all elements betweenx
andn
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.
Try here before watching the video.
Video Explanation
Java Code
class Solution {
public int pivotInteger(int n) {
int sumOfN = (n * (n + 1)) / 2;
int sqrtOfSum = (int)Math.sqrt(sumOfN);
return (sqrtOfSum * sqrtOfSum) == sumOfN ? sqrtOfSum : -1;
}
}
C++ Code
class Solution {
public:
int pivotInteger(int n) {
int sumOfN = (n * (n + 1)) / 2;
int sqrtOfSum = static_cast<int>(sqrt(sumOfN));
return (sqrtOfSum * sqrtOfSum) == sumOfN ? sqrtOfSum : -1;
}
};
Python Code
class Solution:
def pivotInteger(self, n: int) -> int:
sum_of_n = (n * (n + 1)) // 2
sqrt_of_sum = int(math.sqrt(sum_of_n))
return sqrt_of_sum if sqrt_of_sum * sqrt_of_sum == sum_of_n else -1
Javascript Code
var pivotInteger = function(n) {
let sumOfN = (n * (n + 1)) / 2;
let sqrtOfSum = Math.floor(Math.sqrt(sumOfN));
return sqrtOfSum * sqrtOfSum === sumOfN ? sqrtOfSum : -1;
};
Go Code
func pivotInteger(n int) int {
sumOfN := (n * (n + 1)) / 2
sqrtOfSum := int(math.Sqrt(float64(sumOfN)))
if sqrtOfSum*sqrtOfSum == sumOfN {
return sqrtOfSum
}
return -1
}
Complexity Analysis
Time Complexity: O(1)
Space Complexity: O(1)