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.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [2,0,1,3], nums2 = [0,1,2,3]
Output: 1
💡 Note: The triplet (0,1,3) is good: positions in nums1 are (1,2,3) and in nums2 are (0,1,3), both increasing.
Example 2 — No Valid Triplets
$ Input: nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]
Output: 4
💡 Note: Multiple valid triplets exist with the given position constraints.
Example 3 — Minimum Size
$ Input: nums1 = [1,2,0], nums2 = [0,1,2]
Output: 0
💡 Note: No valid triplets possible with these position arrangements.

Constraints

  • n == nums1.length == nums2.length
  • 3 ≤ n ≤ 100
  • 0 ≤ nums1[i], nums2[i] ≤ n - 1
  • nums1 and nums2 are permutations of [0, 1, ..., n - 1].

Visualization

Tap to expand
Count Good Triplets in an Array INPUT nums1 = [2, 0, 1, 3] 2 0 1 3 i=0 i=1 i=2 i=3 nums2 = [0, 1, 2, 3] 0 1 2 3 i=0 i=1 i=2 i=3 Position Mapping (pos2 for nums1): val 2: pos1=0, pos2=2 val 0: pos1=1, pos2=0 val 1: pos1=2, pos2=1 val 3: pos1=3, pos2=3 Mapped array: [2, 0, 1, 3] (pos2 values in nums1 order) ALGORITHM STEPS 1 Build Position Map Map nums2 positions to nums1 2 Use Merge Sort Count left elements smaller 3 Count Right Elements Elements larger on right side 4 Multiply Counts left[i] * right[i] for each i Merge Sort Counting Array: [2, 0, 1, 3] left[]: [0, 0, 0, 0] right[]: [1, 0, 0, 0] For val 0 (middle): left=0, right=2 --> 0*2=0 For val 1: left=0, right=1 For val 2: left=0, right=1 FINAL RESULT Good Triplet Found: (0, 1, 3) nums1: pos(0)=1 < pos(1)=2 < pos(3)=3 nums2: pos(0)=0 < pos(1)=1 < pos(3)=3 Calculation: For each middle element: i=0 (val 2): 0 * 1 = 0 i=1 (val 0): 0 * 2 = 0 i=2 (val 1): 1 * 1 = 1 i=3 (val 3): 3 * 0 = 0 OUTPUT 1 Total: 0+0+1+0 = 1 Key Insight: Transform the problem: map positions from nums2 to nums1 order, then count triplets where middle element has smaller elements on left AND larger elements on right. Merge sort efficiently counts inversions in O(n log n), giving left[i] * right[i] pairs for each middle position i. TutorialsPoint - Count Good Triplets in an Array | Merge Sort with Inversion Count Time: O(n log n) | Space: O(n)
Asked in
Google 15 Facebook 12 Amazon 8
15.4K Views
Medium Frequency
~35 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen