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: Find Triplets with Increasing Positionsnums1 = [2,0,1,3]2013pos 0pos 1pos 2pos 3nums2 = [0,1,2,3]0123pos 0pos 1pos 2pos 3Checking triplet (0,1,3):nums1 positions: 1 < 2 < 3 ✓nums2 positions: 0 < 1 < 3 ✓Valid triplet found!Total count: 1 good tripletStrategy: For each middle element, count valid left × right pairs
Understanding the Visualization
1
Input Arrays
Two permutation arrays with position constraints
2
Position Analysis
Find elements with increasing positions in both arrays
3
Count Triplets
Count all valid triplet combinations
Key Takeaway
🎯 Key Insight: Fix middle elements and count valid left/right pairs that maintain position order in both arrays
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