Skip to content

Commit f219af0

Browse files
committed
Apr 15
1 parent 575045a commit f219af0

File tree

2 files changed

+54
-2
lines changed

2 files changed

+54
-2
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class BIT:
2+
def __init__(self, size: int) -> None:
3+
self.tree = [0] * (size + 1)
4+
5+
def update(self, i: int, delta: int) -> None:
6+
i += 1
7+
while i < len(self.tree):
8+
self.tree[i] += delta
9+
i += i & -i
10+
11+
def query(self, i: int) -> int:
12+
res = 0
13+
i += 1
14+
while i > 0:
15+
res += self.tree[i]
16+
i -= i & -i
17+
return res
18+
19+
20+
class Solution:
21+
def goodTriplets(self, nums1: list[int], nums2: list[int]) -> int:
22+
n = len(nums1)
23+
pos2 = {num: idx for idx, num in enumerate(nums2)}
24+
left, right = [0] * n, [0] * n
25+
26+
bit = BIT(n)
27+
for y in nums1:
28+
j = pos2[y]
29+
left[y] = bit.query(j - 1)
30+
bit.update(j, 1)
31+
32+
bit = BIT(n)
33+
for y in reversed(nums1):
34+
j = pos2[y]
35+
right[y] = bit.query(n - 1) - bit.query(j)
36+
bit.update(j, 1)
37+
38+
return sum(l * r for l, r in zip(left, right))
39+
40+
41+
def main():
42+
nums1 = [2, 0, 1, 3]
43+
nums2 = [0, 1, 2, 3]
44+
assert Solution().goodTriplets(nums1, nums2) == 1
45+
46+
nums1 = [4, 0, 1, 3, 2]
47+
nums2 = [4, 1, 0, 2, 3]
48+
assert Solution().goodTriplets(nums1, nums2) == 4
49+
50+
51+
if __name__ == '__main__':
52+
main()

2025-04-April-LeetCoding-Challenge/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
| April 12 | [3272. Find the Count of Good Integers](https://leetcode.com/problems/find-the-count-of-good-integers/) | Hard | Unsolved |
1919
| April 13 | [1922. Count Good Numbers](https://leetcode.com/problems/count-good-numbers/) | Medium | Unsolved |
2020
| April 14 | [1534. Count Good Triplets](https://leetcode.com/problems/count-good-triplets/) | Easy | Solved |
21-
| April 15 | []() | | |
21+
| April 15 | [2179. Count Good Triplets in an Array](https://leetcode.com/problems/count-good-triplets-in-an-array/) | Hard | Unsolved |
2222
| April 16 | []() | | |
2323
| April 17 | []() | | |
2424
| April 18 | []() | | |
@@ -41,4 +41,4 @@
4141
| --- | --- | --- | --- |
4242
| Easy | 5 | 5 | 0 |
4343
| Medium | 7 | 5 | 2 |
44-
| Hard | 2 | 0 | 2 |
44+
| Hard | 3 | 0 | 3 |

0 commit comments

Comments
 (0)