Skip to content

Commit a7fb607

Browse files
committed
Sync LeetCode submission Runtime - 66 ms (84.05%), Memory - 38.8 MB (59.29%)
1 parent 49303f2 commit a7fb607

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-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: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Approach: Hash Map
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def countBadPairs(self, nums: List[int]) -> int:
8+
bad_pairs = 0
9+
diff_count = {}
10+
11+
for pos in range(len(nums)):
12+
diff = pos - nums[pos]
13+
14+
good_pairs_count = diff_count.get(diff, 0)
15+
16+
bad_pairs += pos - good_pairs_count
17+
18+
diff_count[diff] = good_pairs_count + 1
19+
20+
return bad_pairs
21+

0 commit comments

Comments
 (0)