Skip to content

Commit 252918c

Browse files
committed
[LeetCode Sync] Runtime - 65 ms (84.83%), Memory - 38.8 MB (83.18%)
1 parent e8b82ab commit 252918c

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. A pair of indices <code>(i, j)</code> is a <strong>bad pair</strong> if <code>i &lt; j</code> and <code>j - i != nums[j] - nums[i]</code>.</p>
2+
3+
<p>Return<em> the total number of <strong>bad pairs</strong> in </em><code>nums</code>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> nums = [4,1,3,3]
10+
<strong>Output:</strong> 5
11+
<strong>Explanation:</strong> The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.
12+
The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.
13+
The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.
14+
The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.
15+
The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.
16+
There are a total of 5 bad pairs, so we return 5.
17+
</pre>
18+
19+
<p><strong class="example">Example 2:</strong></p>
20+
21+
<pre>
22+
<strong>Input:</strong> nums = [1,2,3,4,5]
23+
<strong>Output:</strong> 0
24+
<strong>Explanation:</strong> There are no bad pairs.
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>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
33+
</ul>
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution:
2+
def countBadPairs(self, nums: List[int]) -> int:
3+
res = 0
4+
cnt = {} # hashmap
5+
6+
for i in range(len(nums)):
7+
# i - nums[i] is the intuition
8+
diff = i - nums[i]
9+
10+
# count previous positions with same difference
11+
c = cnt.get(diff, 0)
12+
13+
res += i - c
14+
cnt[diff] = c + 1
15+
16+
return res

0 commit comments

Comments
 (0)