2485. Find the Pivot Integer LeetCode Solution

In this guide, you will get 2485. Find the Pivot Integer LeetCode Solution with the best time and space complexity. The solution to Find the Pivot Integer problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Find the Pivot Integer solution in C++
  4. Find the Pivot Integer solution in Java
  5. Find the Pivot Integer solution in Python
  6. Additional Resources
2485. Find the Pivot Integer LeetCode Solution image

Problem Statement of Find the Pivot Integer

Given a positive integer n, find the pivot integer x such that:

The sum of all elements between 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 <= 1000

Complexity Analysis

  • Time Complexity: O(1)
  • Space Complexity: O(1)

2485. Find the Pivot Integer LeetCode Solution in C++

class Solution {
 public:
  int pivotInteger(int n) {
    // 1 + 2 + ... + x = x + ... + n
    // (1 + x) * x / 2 = (x + n) * (n - x + 1) / 2
    //         x + x^2 = nx - x^2 + x + n^2 - nx + n
    //         2 * x^2 = n^2 + n
    //               x = sqrt((n^2 + n) / 2)
    const int y = (n * n + n) / 2;
    const int x = sqrt(y);
    return x * x == y ? x : -1;
  }
};
/* code provided by PROGIEZ */

2485. Find the Pivot Integer LeetCode Solution in Java

class Solution {
  public int pivotInteger(int n) {
    // 1 + 2 + ... + x = x + ... + n
    // (1 + x) * x / 2 = (x + n) * (n - x + 1) / 2
    //         x + x^2 = nx - x^2 + x + n^2 - nx + n
    //         2 * x^2 = n^2 + n
    //               x = sqrt((n^2 + n) / 2)
    final int y = (n * n + n) / 2;
    final int x = (int) Math.sqrt(y);
    return x * x == y ? x : -1;
  }
}
// code provided by PROGIEZ

2485. Find the Pivot Integer LeetCode Solution in Python

class Solution:
  def pivotInteger(self, n: int) -> int:
    # 1 + 2 + ... + x = x + ... + n
    # (1 + x) * x // 2 = (x + n) * (n - x + 1) // 2
    #         x + x^2 = nx - x^2 + x + n^2 - nx + n
    #         2 * x^2 = n^2 + n
    #               x = sqrt((n^2 + n) // 2)
    y = (n * n + n) // 2
    x = math.isqrt(y)
    return x if x * x == y else -1
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.