-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sync LeetCode submission Runtime - 62 ms (32.10%), Memory - 49.1 MB (…
…48.61%)
- Loading branch information
1 parent
971fafb
commit 86b1f40
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
<p>Given a positive integer <code>n</code>, find the <strong>pivot integer</strong> <code>x</code> such that:</p> | ||
|
||
<ul> | ||
<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> | ||
</ul> | ||
|
||
<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> | ||
|
||
<p> </p> | ||
<p><strong class="example">Example 1:</strong></p> | ||
|
||
<pre> | ||
<strong>Input:</strong> n = 8 | ||
<strong>Output:</strong> 6 | ||
<strong>Explanation:</strong> 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21. | ||
</pre> | ||
|
||
<p><strong class="example">Example 2:</strong></p> | ||
|
||
<pre> | ||
<strong>Input:</strong> n = 1 | ||
<strong>Output:</strong> 1 | ||
<strong>Explanation:</strong> 1 is the pivot integer since: 1 = 1. | ||
</pre> | ||
|
||
<p><strong class="example">Example 3:</strong></p> | ||
|
||
<pre> | ||
<strong>Input:</strong> n = 4 | ||
<strong>Output:</strong> -1 | ||
<strong>Explanation:</strong> It can be proved that no such integer exist. | ||
</pre> | ||
|
||
<p> </p> | ||
<p><strong>Constraints:</strong></p> | ||
|
||
<ul> | ||
<li><code>1 <= n <= 1000</code></li> | ||
</ul> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
/** | ||
* @param {number} n | ||
* @return {number} | ||
*/ | ||
var pivotInteger = function(n) { | ||
for(let i=1;i<=n;i++){ | ||
// using arithmetic progression | ||
let leftSum = (i * (i+1)) / 2; // sum of elements from 1 to i | ||
let rightSum = ((n*(n+1)) / 2 ) - ((i * (i-1)) / 2); // sum of elements from i to n | ||
|
||
if(leftSum === rightSum){ | ||
return i; | ||
} | ||
} | ||
return -1; | ||
}; |