2367. Number of Arithmetic Triplets LeetCode Solution
In this guide, you will get 2367. Number of Arithmetic Triplets LeetCode Solution with the best time and space complexity. The solution to Number of Arithmetic Triplets problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Number of Arithmetic Triplets solution in C++
- Number of Arithmetic Triplets solution in Java
- Number of Arithmetic Triplets solution in Python
- Additional Resources
Problem Statement of Number of Arithmetic Triplets
You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met:
i < j < k,
nums[j] – nums[i] == diff, and
nums[k] – nums[j] == diff.
Return the number of unique arithmetic triplets.
Example 1:
Input: nums = [0,1,4,6,7,10], diff = 3
Output: 2
Explanation:
(1, 2, 4) is an arithmetic triplet because both 7 – 4 == 3 and 4 – 1 == 3.
(2, 4, 5) is an arithmetic triplet because both 10 – 7 == 3 and 7 – 4 == 3.
Example 2:
Input: nums = [4,5,6,7,8,9], diff = 2
Output: 2
Explanation:
(0, 2, 4) is an arithmetic triplet because both 8 – 6 == 2 and 6 – 4 == 2.
(1, 3, 5) is an arithmetic triplet because both 9 – 7 == 2 and 7 – 5 == 2.
Constraints:
3 <= nums.length <= 200
0 <= nums[i] <= 200
1 <= diff <= 50
nums is strictly increasing.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(200) = O(1)
2367. Number of Arithmetic Triplets LeetCode Solution in C++
class Solution {
public:
int arithmeticTriplets(vector<int>& nums, int diff) {
constexpr int kMax = 200;
int ans = 0;
vector<bool> count(kMax + 1);
for (const int num : nums) {
if (num >= 2 * diff && count[num - diff] && count[num - 2 * diff])
++ans;
count[num] = true;
}
return ans;
}
};
/* code provided by PROGIEZ */
2367. Number of Arithmetic Triplets LeetCode Solution in Java
class Solution {
public int arithmeticTriplets(int[] nums, int diff) {
final int kMax = 200;
int ans = 0;
boolean[] count = new boolean[kMax + 1];
for (final int num : nums) {
if (num >= 2 * diff && count[num - diff] && count[num - 2 * diff])
++ans;
count[num] = true;
}
return ans;
}
}
// code provided by PROGIEZ
2367. Number of Arithmetic Triplets LeetCode Solution in Python
class Solution:
def arithmeticTriplets(self, nums: list[int], diff: int) -> int:
kMax = 200
ans = 0
count = [False] * (kMax + 1)
for num in nums:
if num >= 2 * diff and count[num - diff] and count[num - 2 * diff]:
ans += 1
count[num] = True
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.