Count Good Triplets in an Array — LeetCode 2179 Python Solution
- Problem
- #2179
- Pattern
- Monotonic Stack
- Reading time
- 6 min
- Source
- leetcode.com
The problem
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.
Example
- 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).
Python solution
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \log n), where n is the length of the array \textit{nums1} |
| Space | O(n) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 2179. Count Good Triplets in an Array is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2179. Count Good Triplets in an Array?
- LeetCode 2179. Count Good Triplets in an Array is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2179. Count Good Triplets in an Array?
- The Python solution on this page runs in O(n \log n), where n is the length of the array \textit{nums1}.
- What is the space complexity of LeetCode 2179. Count Good Triplets in an Array?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2179. Count Good Triplets in an Array cover?
- LeetCode 2179. Count Good Triplets in an Array is tagged Binary Indexed Tree, Segment Tree, Array, Binary Search, Divide and Conquer, Ordered Set and Merge Sort on LeetCode.