Count Good Triplets in an Array Problem
Description
LeetCode Problem 2179.
You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1].
A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1_v as the index of the value v in nums1 and pos2_v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1_x < pos1_y < pos1_z and pos2_x < pos2_y < pos2_z.
Return the total number of good triplets.
Example 1:
Input: nums1 = [2,0,1,3], nums2 = [0,1,2,3]
Output: 1
Explanation:
There are 4 triplets (x,y,z) such that pos1_x < pos1_y < pos1_z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3).
Out of those triplets, only the triplet (0,1,3) satisfies pos2_x < pos2_y < pos2_z. Hence, there is only 1 good triplet.
Example 2:
Input: nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]
Output: 4
Explanation: The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).
Constraints:
n == nums1.length == nums2.length3 <= n <= 10^50 <= nums1[i], nums2[i] <= n - 1nums1andnums2are permutations of[0, 1, ..., n - 1].
Solution
Approach: Binary indexed tree (Fenwick tree)
A good triplet (x, y, z) has x, y, z in increasing order of position in both arrays. Count the triplets by their middle value y.
Let pos[v] be the position of v in nums2. Walk through nums1 from left to right. When we reach a value y, every value already visited sits before y in nums1, so we only need to know how many of them are also before y in nums2, and how many values after y in nums1 are also after it in nums2.
Keep a Fenwick tree over positions of nums2, where position p holds 1 once its value has been visited. For the current y at position p:
left = query(p)is the number of visited values beforeyinnums2. These are valid choices forx.- Values not yet visited and after
pinnums2are valid choices forz: there are(n - p)positions afterp, of which(visited - left)are already visited, soright = (n - p) - (visited - left).
Add left * right to the answer, then mark position p as visited. Here visited is the number of values processed so far, which is simply the loop index.
Complexity: time O(n log n), space O(n), where n is the length of the arrays.
class BinaryIndexedTree:
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
@staticmethod
def lowbit(x):
return x & -x
def update(self, x, delta):
while x <= self.n:
self.c[x] += delta
x += BinaryIndexedTree.lowbit(x)
def query(self, x):
s = 0
while x > 0:
s += self.c[x]
x -= BinaryIndexedTree.lowbit(x)
return s
class Solution:
def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int:
pos = {v: i for i, v in enumerate(nums2, 1)}
ans = 0
n = len(nums1)
tree = BinaryIndexedTree(n)
for num in nums1:
p = pos[num]
left = tree.query(p)
right = n - p - (tree.query(n) - tree.query(p))
ans += left * right
tree.update(p, 1)
return ans