LeetCode 2179: Count Good Triplets in an Array Solution
Master LeetCode problem 2179 (Count Good Triplets in an Array), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2179. Count Good Triplets in an Array
Problem Explanation
Explanation
- To solve this problem, we iterate through both arrays
nums1andnums2. - For each value in
nums1, we find its position innums2and store it in a hashmap. - We then iterate through all possible triplets in
nums1and check if they form a good triplet with increasing positions innums2. - If a triplet is found to be good, we increment the count.
- Finally, we return the total count of good triplets.
Time Complexity: O(n^2)
Space Complexity: O(n)
Solution Code
class Solution {
public int countGoodTriplets(int[] nums1, int[] nums2) {
int n = nums1.length;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(nums2[i], i);
}
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
for (int k = j+1; k < n; k++) {
if (nums1[i] < nums1[j] && nums1[j] < nums1[k] && map.get(nums1[i]) < map.get(nums1[j]) && map.get(nums1[j]) < map.get(nums1[k])) {
count++;
}
}
}
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2179 (Count Good Triplets in an Array)?
This page provides optimized solutions for LeetCode problem 2179 (Count Good Triplets in an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2179 (Count Good Triplets in an Array)?
The time complexity for LeetCode 2179 (Count Good Triplets in an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2179 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2179 in Java, C++, or Python.