Skip to content

Commit 0a766a0

Browse files
Create 2179_Count_Good_Triplet_in_an_Array.java
1 parent a226ef7 commit 0a766a0

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// Problem Number: 2179
2+
3+
// Count Good Triplet in an Array.
4+
5+
class FenwickTree {
6+
public FenwickTree(int n) {
7+
sums = new int[n + 1];
8+
}
9+
10+
public void add(int i, int delta) {
11+
while (i < sums.length) {
12+
sums[i] += delta;
13+
i += lowbit(i);
14+
}
15+
}
16+
17+
public int get(int i) {
18+
int sum = 0;
19+
while (i > 0) {
20+
sum += sums[i];
21+
i -= lowbit(i);
22+
}
23+
return sum;
24+
}
25+
26+
private int[] sums;
27+
28+
private static int lowbit(int i) {
29+
return i & -i;
30+
}
31+
}
32+
33+
class Solution {
34+
public long goodTriplets(int[] nums1, int[] nums2) {
35+
final int n = nums1.length;
36+
long ans = 0;
37+
Map<Integer, Integer> numToIndex = new HashMap<>();
38+
int[] arr = new int[n];
39+
int[] leftSmaller = new int[n];
40+
int[] rightLarger = new int[n];
41+
FenwickTree tree1 = new FenwickTree(n);
42+
FenwickTree tree2 = new FenwickTree(n);
43+
44+
for (int i = 0; i < n; ++i)
45+
numToIndex.put(nums1[i], i);
46+
47+
for (int i = 0; i < n; ++i)
48+
arr[i] = numToIndex.get(nums2[i]);
49+
50+
for (int i = 0; i < n; ++i) {
51+
leftSmaller[i] = tree1.get(arr[i]);
52+
tree1.add(arr[i] + 1, 1);
53+
}
54+
55+
for (int i = n - 1; i >= 0; --i) {
56+
rightLarger[i] = tree2.get(n) - tree2.get(arr[i]);
57+
tree2.add(arr[i] + 1, 1);
58+
}
59+
60+
for (int i = 0; i < n; ++i)
61+
ans += (long) leftSmaller[i] * rightLarger[i];
62+
63+
return ans;
64+
}
65+
}

0 commit comments

Comments
 (0)