Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Count Good Triplets in an Array

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2179" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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 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. Example 1: 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: 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). Constraints: n == nums1.length == nums2.length 3 <= n <= 105 0 <= nums1[i], nums2[i] <= n - 1 nums1 and nums2 are permutations of [0, 1, ..., n - 1].

Explanation

Here's a breakdown of the solution approach, followed by the code:

  • Core Idea: The problem can be solved efficiently by iterating through each element of nums1 and considering it as the middle element y of a potential good triplet (x, y, z). For each y, we need to count how many elements x appear before y in nums1 and also before y in nums2, and how many elements z appear after y in nums1 and also after y in nums2. Multiplying these counts gives the number of good triplets with y as the middle element.
  • Prefix/Suffix Counting: We can use prefix sums (or cumulative counts) to efficiently determine the number of elements smaller than y that appear before y in nums2. This can be done by building a mapping from the values in nums2 to their indices. Then, for each value y in nums1, we can count the number of smaller values that occur to the left of its index in nums2. Similarly, suffix counts can be derived by subtracting prefix from total.
  • Binary Indexed Tree (Fenwick Tree): We'll leverage a Binary Indexed Tree to perform the prefix sum counting. A Fenwick tree allows for efficient updates (incrementing a value at a certain index) and queries (calculating the sum of values up to a certain index) in logarithmic time.

  • Complexity: O(n log n) time complexity, O(n) space complexity.

Code

    class FenwickTree:
    def __init__(self, n):
        self.n = n
        self.tree = [0] * (n + 1)

    def update(self, i, val):
        i += 1  # 1-based indexing
        while i <= self.n:
            self.tree[i] += val
            i += i & (-i)

    def query(self, i):
        i += 1  # 1-based indexing
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & (-i)
        return s

def goodTriplets(nums1, nums2):
    n = len(nums1)
    pos2 = [0] * n
    for i in range(n):
        pos2[nums2[i]] = i

    ans = 0
    for j in range(n):
        y = nums1[j]
        pos1_y = j
        pos2_y = pos2[y]

        smaller_left = 0
        larger_right = 0

        ft = FenwickTree(n)

        # Count smaller elements to the left in nums2
        for i in range(0, pos1_y):
            x = nums1[i]
            if pos2[x] < pos2_y:
                smaller_left += 1

        # Count larger elements to the right in nums2
        for i in range(pos1_y + 1, n):
            z = nums1[i]
            if pos2[z] > pos2_y:
                larger_right += 1

        ans += smaller_left * larger_right

    return ans

More from this blog

C

Chatmagic blog

2894 posts