Skip to content

Commit 86b1f40

Browse files
committed
Sync LeetCode submission Runtime - 62 ms (32.10%), Memory - 49.1 MB (48.61%)
1 parent 971fafb commit 86b1f40

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

2571-find-the-pivot-integer/README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<p>Given a positive integer <code>n</code>, find the <strong>pivot integer</strong> <code>x</code> such that:</p>
2+
3+
<ul>
4+
<li>The sum of all elements between <code>1</code> and <code>x</code> inclusively equals the sum of all elements between <code>x</code> and <code>n</code> inclusively.</li>
5+
</ul>
6+
7+
<p>Return <em>the pivot integer </em><code>x</code>. If no such integer exists, return <code>-1</code>. It is guaranteed that there will be at most one pivot index for the given input.</p>
8+
9+
<p>&nbsp;</p>
10+
<p><strong class="example">Example 1:</strong></p>
11+
12+
<pre>
13+
<strong>Input:</strong> n = 8
14+
<strong>Output:</strong> 6
15+
<strong>Explanation:</strong> 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21.
16+
</pre>
17+
18+
<p><strong class="example">Example 2:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> n = 1
22+
<strong>Output:</strong> 1
23+
<strong>Explanation:</strong> 1 is the pivot integer since: 1 = 1.
24+
</pre>
25+
26+
<p><strong class="example">Example 3:</strong></p>
27+
28+
<pre>
29+
<strong>Input:</strong> n = 4
30+
<strong>Output:</strong> -1
31+
<strong>Explanation:</strong> It can be proved that no such integer exist.
32+
</pre>
33+
34+
<p>&nbsp;</p>
35+
<p><strong>Constraints:</strong></p>
36+
37+
<ul>
38+
<li><code>1 &lt;= n &lt;= 1000</code></li>
39+
</ul>
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* @param {number} n
3+
* @return {number}
4+
*/
5+
var pivotInteger = function(n) {
6+
for(let i=1;i<=n;i++){
7+
// using arithmetic progression
8+
let leftSum = (i * (i+1)) / 2; // sum of elements from 1 to i
9+
let rightSum = ((n*(n+1)) / 2 ) - ((i * (i-1)) / 2); // sum of elements from i to n
10+
11+
if(leftSum === rightSum){
12+
return i;
13+
}
14+
}
15+
return -1;
16+
};

0 commit comments

Comments
 (0)