- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 67 lines of C++ from the credited upstream file 2179.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 7 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class FenwickTree {2 public:3 FenwickTree(int n) : sums(n + 1) {}4 5 void add(int i, int delta) {6 while (i < sums.size()) {7 sums[i] += delta;8 i += lowbit(i);9 }10 }11 12 int get(int i) const {13 int sum = 0;14 while (i > 0) {15 sum += sums[i];16 i -= lowbit(i);17 }18 return sum;19 }20 21 private:22 vector<int> sums;23 24 static inline int lowbit(int i) {25 return i & -i;26 }27};28 29class Solution {30 public:31 long long goodTriplets(vector<int>& nums1, vector<int>& nums2) {32 const int n = nums1.size();33 long ans = 0;34 unordered_map<int, int> numToIndex;35 vector<int> arr;36 37 vector<int> leftSmaller(n);38 39 vector<int> rightLarger(n);40 FenwickTree tree1(n); 41 FenwickTree tree2(n); 42 43 for (int i = 0; i < n; ++i)44 numToIndex[nums1[i]] = i;45 46 47 48 for (const int num : nums2)49 arr.push_back(numToIndex[num]);50 51 for (int i = 0; i < n; ++i) {52 leftSmaller[i] = tree1.get(arr[i]);53 tree1.add(arr[i] + 1, 1);54 }55 56 for (int i = n - 1; i >= 0; --i) {57 rightLarger[i] = tree2.get(n) - tree2.get(arr[i]);58 tree2.add(arr[i] + 1, 1);59 }60 61 for (int i = 0; i < n; ++i)62 ans += static_cast<long>(leftSmaller[i]) * rightLarger[i];63 64 return ans;65 }66};67