Leetcode problem 58 - 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.
/**
* @param {number[]} nums
* @param {number} diff
* @return {number}
*/
var arithmeticTriplets = function(nums, diff) {
// Create a map to store elements from the nums array.
let map = new Map()
// Initialize a count variable with the value 0.
let count = 0;
// Iterate trough nums array using a for loop
for(let i = 0; i < nums.length; i++){
// For each element nums[i], check if map contains two elements: one where the current element is reduced by the 'diff' value and another where the current element is reduced by 'diff' value twice.
if(map.has(nums[i] - diff) && map.has(nums[i] - diff - diff)){
// If so, increment count value.
count++
}
// Set the current element in map
map.set(nums[i])
}
// return count
return count;
};
You start by initializing an empty Map
called map
to store elements from the nums
array.
The variable count
is initialized to 0. This variable will be used to keep track of the count of triplets that satisfy the condition.
You iterate through the nums
array using a for
loop.
For each element nums[i]
, you check if map
contains two elements: nums[i] - diff
and nums[i] - diff - diff
. In other words, you are looking for two previous elements in the array such that the difference between the current element and those two previous elements is equal to diff
.
If both conditions are met, you increment the count
by 1, indicating that you’ve found a triplet that satisfies the condition.
After checking the conditions, you add the current element nums[i]
to the map
using map.set(nums[i])
. This step ensures that you have a record of the current element in the map for future iterations.
The loop continues to the next element in the nums
array, and the process repeats.
Finally, you return the count
, which represents the total number of triplets in the nums
array that satisfy the condition.
The time complexity of the code is O(n), where n is the length of the nums array. The primary loop iterates through each element in the nums array exactly once.
Leave a comment