#2179

Count Good Triplets in an Array

Hard
ArrayBinary SearchDivide and ConquerBinary Indexed TreeSegment TreeMerge SortOrdered SetFenwick TreeCountingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

We can optimize the solution by using a combination of counting and data structures to efficiently track the number of valid triplets without checking every combination explicitly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create position mappings pos1 and pos2 for nums1 and nums2 respectively.
  2. 2Step 2: For each element y in nums2, count how many elements x come before y in both arrays using a Fenwick Tree (or Binary Indexed Tree).
  3. 3Step 3: For each element y, count how many elements z come after y in both arrays using a Fenwick Tree.
  4. 4Step 4: Multiply the counts from Step 2 and Step 3 for each y to get the total number of good triplets.
solution.py28 lines
1def countGoodTriplets(nums1, nums2):
2    n = len(nums1)
3    pos1 = {v: i for i, v in enumerate(nums1)}
4    pos2 = {v: i for i, v in enumerate(nums2)}
5    fenwick1 = [0] * (n + 1)
6    fenwick2 = [0] * (n + 1)
7
8    def update(fenwick, index, value):
9        while index <= n:
10            fenwick[index] += value
11            index += index & -index
12
13    def query(fenwick, index):
14        total = 0
15        while index > 0:
16            total += fenwick[index]
17            index -= index & -index
18        return total
19
20    count = 0
21    for y in range(n):
22        count_x = query(fenwick1, pos2[y])
23        count_z = query(fenwick2, n) - query(fenwick2, pos2[y])
24        count += count_x * count_z
25        update(fenwick1, pos2[y] + 1, 1)
26        update(fenwick2, pos2[y] + 1, 1)
27
28    return count

Complexity note: The complexity is O(n log n) due to the use of Fenwick Trees for counting, which allows us to efficiently update and query counts.

  • 1Understanding the relationship between positions in both arrays is crucial for identifying good triplets.
  • 2Using efficient data structures like Fenwick Trees can significantly reduce the time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.