#2367

Number of Arithmetic Triplets

Easy
ArrayHash TableTwo PointersEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a HashSet allows us to quickly check if the required numbers to form an arithmetic triplet exist, reducing the need for nested loops and improving efficiency.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a HashSet to store the numbers in the array for quick lookup.
  2. 2Step 2: Iterate through the array and for each number, check if both (num + diff) and (num + 2 * diff) exist in the HashSet.
  3. 3Step 3: If both numbers exist, increment the count of valid triplets.
solution.py12 lines
1# Full working Python code
2
3def count_arithmetic_triplets(nums, diff):
4    num_set = set(nums)
5    count = 0
6    for num in nums:
7        if (num + diff) in num_set and (num + 2 * diff) in num_set:
8            count += 1
9    return count
10
11# Example usage
12print(count_arithmetic_triplets([0,1,4,6,7,10], 3))

Complexity note: The time complexity is O(n) because we only traverse the array a couple of times. The space complexity is O(n) due to the HashSet storing the numbers for quick lookup.

  • 1Using a HashSet allows for O(1) average time complexity for lookups.
  • 2The problem can be solved efficiently by recognizing the arithmetic sequence properties.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.