Skip to content

Commit a55c860

Browse files
committed
Sync LeetCode submission Runtime - 95 ms (100.00%), Memory - 30.6 MB (91.73%)
1 parent 6d8f5af commit a55c860

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<p>Given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of fair pairs</em>.</p>
2+
3+
<p>A pair <code>(i, j)</code> is <b>fair </b>if:</p>
4+
5+
<ul>
6+
<li><code>0 &lt;= i &lt; j &lt; n</code>, and</li>
7+
<li><code>lower &lt;= nums[i] + nums[j] &lt;= upper</code></li>
8+
</ul>
9+
10+
<p>&nbsp;</p>
11+
<p><strong class="example">Example 1:</strong></p>
12+
13+
<pre>
14+
<strong>Input:</strong> nums = [0,1,7,4,4,5], lower = 3, upper = 6
15+
<strong>Output:</strong> 6
16+
<strong>Explanation:</strong> There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5).
17+
</pre>
18+
19+
<p><strong class="example">Example 2:</strong></p>
20+
21+
<pre>
22+
<strong>Input:</strong> nums = [1,7,9,2,5], lower = 11, upper = 11
23+
<strong>Output:</strong> 1
24+
<strong>Explanation:</strong> There is a single fair pair: (2,3).
25+
</pre>
26+
27+
<p>&nbsp;</p>
28+
<p><strong>Constraints:</strong></p>
29+
30+
<ul>
31+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
32+
<li><code>nums.length == n</code></li>
33+
<li><code><font face="monospace">-10<sup>9</sup></font>&nbsp;&lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
34+
<li><code><font face="monospace">-10<sup>9</sup>&nbsp;&lt;= lower &lt;= upper &lt;= 10<sup>9</sup></font></code></li>
35+
</ul>
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Approach 2: Two Pointer
2+
3+
# Time: O(n log n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:
8+
nums.sort()
9+
return self.lower_bound(nums, upper + 1) - self.lower_bound(nums, lower)
10+
11+
# Calculate the number of pairs with sum less than `value`.
12+
def lower_bound(self, nums, value):
13+
left, right = 0, len(nums) - 1
14+
result = 0
15+
16+
while left < right:
17+
if nums[left] + nums[right] < value:
18+
# If sum is less than value, add the size of window to result and move to the next index
19+
result += right - left
20+
left += 1
21+
else:
22+
# Otherwise, shift the right pointer backwards, until we get a valid window.
23+
right -= 1
24+
25+
return result
26+

0 commit comments

Comments
 (0)