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 value v in nums1 and pos2[v] as the index of 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]ANDpos2[x] < pos2[y] < pos2[z]
Return the total number of good triplets.
Example: If nums1 = [2, 0, 1, 3] and nums2 = [0, 1, 2, 3], then value 0 appears at position 1 in nums1 and position 0 in nums2. The triplet (0, 1, 3) is good because positions in nums1 are [1, 2, 3] (increasing) and positions in nums2 are [0, 1, 3] (also increasing).
Input & Output
Visualization
Time & Space Complexity
Each element is processed once with O(log n) BIT operations
Space for position arrays and BIT structure
Constraints
- n == nums1.length == nums2.length
- 3 โค n โค 105
- 0 โค nums1[i], nums2[i] โค n - 1
- nums1 and nums2 are permutations of [0, 1, ..., n - 1]
- All values in each array are distinct