Problem

You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1].

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 pos1v as the index of the value v in nums1 and pos2v 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 pos1x < pos1y < pos1z and pos2x < pos2y < pos2z.

Return the total number of good triplets.

Examples

Example 1:

1
2
3
4
5
Input: nums1 = [2,0,1,3], nums2 = [0,1,2,3]
Output: 1
Explanation: 
There are 4 triplets (x,y,z) such that pos1x < pos1y < pos1z. 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 pos2x < pos2y < pos2z. Hence, there is only 1 good triplet.

Example 2:

1
2
3
4
5
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).

Solution

Method 1 - Using Fenwick Tree

Here is the approach:

  1. Understanding the problem: We need to ensure that the values xy, and z appear in increasing order by position in both arrays nums1 and nums2. Positions can be determined by creating a mapping of values to indices for both arrays.
  2. Mapping positions: Since nums1 and nums2 are permutations of [0, 1, ..., n-1], we can create a position mapping (e.g., pos1 for nums1 and pos2 for nums2).
  3. Core logic: Once positions are mapped, the task reduces to counting all triplets (x, y, z) such that:
    • pos1[x] < pos1[y] < pos1[z]
    • pos2[x] < pos2[y] < pos2[z]
  4. Algorithm:
    • Compute positions for nums1 and nums2.
    • Use a combinatorial approach to check all triplets (x, y, z) and validate the conditions.
    • To optimise, leverage techniques like Fenwick Tree or Binary Indexed Tree to count inversions efficiently.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {

    public long goodTriplets(int[] nums1, int[] nums2) {
        int n = nums1.length;

        // Map positions in nums1
        int[] pos1 = new int[n];
        for (int i = 0; i < n; i++) {
            pos1[nums1[i]] = i;
        }

        int[] pos2 = new int[n];
        for (int i = 0; i < n; i++) {
            pos2[i] = pos1[nums2[i]];
        }

        // Fenwick Tree to count increasing triplets
        long ans = 0;
        int[] ftLeft = new int[n + 1];
        int[] ftRight = new int[n + 1];

        // Initialize right Fenwick tree with counts
        for (int v : pos2) {
            fenwickUpdate(ftRight, v + 1, 1, n);
        }

        for (int v : pos2) {
            fenwickUpdate(ftRight, v + 1, -1, n); // Remove current element from right tree
            long leftCount = fenwickQuery(ftLeft, v); // Count smaller elements to the left
            long rightCount =
                fenwickQuery(ftRight, n) - fenwickQuery(ftRight, v); // Count larger elements to the right
            ans += leftCount * rightCount; // Count triplets
            fenwickUpdate(ftLeft, v + 1, 1, n); // Add current element to the left tree
        }

        return ans;
    }

    private void fenwickUpdate(int[] ft, int idx, int val, int size) {
        while (idx <= size) {
            ft[idx] += val;
            idx += idx & -idx;
        }
    }

    private int fenwickQuery(int[] ft, int idx) {
        int s = 0;
        while (idx > 0) {
            s += ft[idx];
            idx -= idx & -idx;
        }
        return s;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution:
    def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int:
        n = len(nums1)
        
        # Map positions in nums1
        pos1 = {v: i for i, v in enumerate(nums1)}
        pos2 = [pos1[v] for v in nums2]
        
        # Fenwick Tree to count increasing triplets
        def fenwick_update(ft: List[int], idx: int, val: int, size: int):
            while idx <= size:
                ft[idx] += val
                idx += idx & -idx

        def fenwick_query(ft: List[int], idx: int) -> int:
            s = 0
            while idx > 0:
                s += ft[idx]
                idx -= idx & -idx
            return s
        
        # Count triplets
        ans = 0
        ft_left = [0] * (n + 1)
        ft_right = [0] * (n + 1)
        
        for v in pos2:
            fenwick_update(ft_right, v + 1, 1, n)
        
        for v in pos2:
            fenwick_update(ft_right, v + 1, -1, n)
            left_count = fenwick_query(ft_left, v)
            right_count = fenwick_query(ft_right, n) - fenwick_query(ft_right, v)
            ans += left_count * right_count
            fenwick_update(ft_left, v + 1, 1, n)
        
        return ans

Complexity

  • ⏰ Time complexity: O(n^2 log n). The naive approach to checking all triplets is O(n^3). However, using advanced techniques, we can reduce it to O(n^2 log n) when using Fenwick Tree/Binary Indexed Tree for counting valid triplets.
  • 🧺 Space complexity: O(n) for storing mappings and auxiliary data structures.