Number of Arithmetic Triplets — LeetCode 2367 Python Solution

EasyArrayHash TableTwo PointersEnumeration
Problem
#2367
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n^3), where n is the length of the array nums
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview