Leetcode 2485: Find the Pivot Integer Solution

Here, we will see how to solve Find the Pivot Integer Solution of leet code 2485 problem.

You are 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.

You have to 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 = 200
Output: -1
Explanation: It can be proved that no such integer exist.```

Find the Pivot Integer Solution in C++ and Go lang:

Here, we will be solving problem in multiple ways with code.

C++ code 1:

```class Solution {
public:
int pivotInteger(int n) {
// Get the total sum from 1 to n
int total = (n * (n + 1)) / 2;
int sum = 0;

for(int i = 1; i <= n; i++) {
sum += i;

if(sum == (total - sum + i)) {
return i;
}
}
return -1;
}
};```

C++ code 2:

```class Solution {
public:
int pivotInteger(int n) {
int total = 0;
for (int i = 1; i <= n; ++i)
total += i;
int pre = 0;
int post = total-1;

for (int i = 1; i <= n; ++i) {
if (pre == post)
return i;
pre += i;
post -= i+1;
}

return -1;
}
};```

C++ code 3:

```class Solution {
public:
int pivotInteger(int n) {

if(n==10) return n;

int sum1=0,sum2=n*(n+1)/2,val=1,i=1;

while(sum2>0)
{
sum1+=i;

if(sum1==sum2)
{
return val;
}

sum2-=i;
val+=1;
i++;
}
return -1;
}
};```

Go code 1:

```func pivotInteger(n int) int {
total := (n * (n + 1)) / 2
sum := 0

for i := 1; i <= n; i++ {
sum += i;

if(sum == (total - sum + i)) {
return i;
}
}
return -1;
}```

Output:

```Input: n = 8
Output: 6```

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

https://www.techieindoor.com/category/leetcode/

Posted in C++, Easy, golang, golang program, Leetcode