Number of Arithmetic Triplets — LeetCode 2367 Python Solution
- Problem
- #2367
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
class Solution:
def arithmeticTriplets(self, nums: List[int], diff: int) -> int:
return sum(b - a == diff and c - b == diff for a, b, c in combinations(nums, 3))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^3), where n is the length of the array nums |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 2367. Number of Arithmetic Triplets is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2367. Number of Arithmetic Triplets?
- LeetCode 2367. Number of Arithmetic Triplets is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2367. Number of Arithmetic Triplets?
- The Python solution on this page runs in O(n^3), where n is the length of the array nums.
- What is the space complexity of LeetCode 2367. Number of Arithmetic Triplets?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2367. Number of Arithmetic Triplets cover?
- LeetCode 2367. Number of Arithmetic Triplets is tagged Array, Hash Table, Two Pointers and Enumeration on LeetCode.