|
| 1 | +/** |
| 2 | + * 2179. Count Good Triplets in an Array |
| 3 | + * https://leetcode.com/problems/count-good-triplets-in-an-array/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations |
| 7 | + * of [0, 1, ..., n - 1]. |
| 8 | + * |
| 9 | + * A good triplet is a set of 3 distinct values which are present in increasing order by position |
| 10 | + * both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in |
| 11 | + * nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) |
| 12 | + * where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. |
| 13 | + * |
| 14 | + * Return the total number of good triplets. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[]} nums1 |
| 19 | + * @param {number[]} nums2 |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var goodTriplets = function(nums1, nums2) { |
| 23 | + const length = nums1.length; |
| 24 | + const pos1 = new Array(length); |
| 25 | + const pos2 = new Array(length); |
| 26 | + |
| 27 | + for (let i = 0; i < length; i++) { |
| 28 | + pos1[nums1[i]] = i; |
| 29 | + pos2[nums2[i]] = i; |
| 30 | + } |
| 31 | + |
| 32 | + const indices = new Array(length); |
| 33 | + for (let i = 0; i < length; i++) { |
| 34 | + indices[pos1[i]] = pos2[i]; |
| 35 | + } |
| 36 | + |
| 37 | + const leftTree = new Array(length + 1).fill(0); |
| 38 | + const rightTree = new Array(length + 1).fill(0); |
| 39 | + |
| 40 | + let result = 0; |
| 41 | + for (let i = length - 1; i >= 0; i--) { |
| 42 | + const position = indices[i]; |
| 43 | + update(rightTree, position, 1); |
| 44 | + } |
| 45 | + |
| 46 | + for (let i = 0; i < length; i++) { |
| 47 | + const position = indices[i]; |
| 48 | + update(rightTree, position, -1); |
| 49 | + const smaller = query(leftTree, position); |
| 50 | + const larger = query(rightTree, length - 1) - query(rightTree, position); |
| 51 | + result += smaller * larger; |
| 52 | + update(leftTree, position, 1); |
| 53 | + } |
| 54 | + |
| 55 | + return result; |
| 56 | + |
| 57 | + function update(tree, index, delta) { |
| 58 | + for (let i = index + 1; i <= length; i += i & -i) { |
| 59 | + tree[i] += delta; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + function query(tree, index) { |
| 64 | + let sum = 0; |
| 65 | + for (let i = index + 1; i > 0; i -= i & -i) { |
| 66 | + sum += tree[i]; |
| 67 | + } |
| 68 | + return sum; |
| 69 | + } |
| 70 | +}; |
0 commit comments