Problem · Array
Count Good Tuples
Learn this problemProblem statement
You are given an integer array a. Consider every tuple of three consecutive elements.
A tuple is good if exactly two of its three values are equal. For example, (2, 1, 2) is a good tuple, while (1, 1, 1) and (1, 2, 3) are not.
Return the number of good tuples in a. Tuples may overlap.
A solution with time complexity no worse than O(a.length^2) fits within the execution time limit.
Function
solution(a: int[]) → intExamples
Example 1
a = [1, 1, 1, 2, 1, 3, 4]return = 2The five consecutive tuples are:
(1, 1, 1): all three values are equal, so this is not a good tuple.(1, 1, 2): exactly two values are equal, so this is a good tuple.(1, 2, 1): exactly two values are equal, so this is a good tuple.(2, 1, 3): all three values are distinct, so this is not a good tuple.(1, 3, 4): all three values are distinct, so this is not a good tuple.
Exactly two tuples are good, so the answer is 2.