Sponsored
We can use a sliding window approach with a counter to track consecutive numbers as we iterate through the list.
Time Complexity: O(n), where n is the number of elements in the list. Space Complexity: O(1).
1function findConsecutiveNumbers(nums) {
2 let result = [];
3 let count = 1;
4 for (let i = 1; i < nums.length; i++) {
5 if (nums[i] === nums[i - 1]) {
6 count++;
7 if (count === 3 && !result.includes(nums[i])) {
8 result.push(nums[i]);
9 }
10 } else {
11 count = 1;
12 }
13 }
14 return result;
15}
16
17const nums = [1, 1, 1, 2, 1, 2, 2];
18console.log(findConsecutiveNumbers(nums));
19
For JavaScript, an array is used to keep track of any number that appears at least thrice in a row. The 'count' variable indicates how many consecutive identical numbers have been encountered.
This approach uses a HashMap (or Dictionary in Python) to keep track of the sequence counts of numbers. This way, we can determine if any number is repeated consecutively at least three times.
Time Complexity: O(n). Space Complexity: O(1) since we use only limited extra space.
1#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
vector<int> findConsecutiveNumbers(vector<int>& nums) {
unordered_map<int, int> count;
vector<int> result;
int consecutive = 1;
for (size_t i = 1; i < nums.size(); ++i) {
if (nums[i] == nums[i - 1]) {
consecutive++;
if (consecutive == 3 && count[nums[i - 1]] != 1) {
result.push_back(nums[i]);
count[nums[i]] = 1;
}
} else {
consecutive = 1;
}
}
return result;
}
int main() {
vector<int> nums = {1, 1, 1, 2, 1, 2, 2};
vector<int> result = findConsecutiveNumbers(nums);
for (int num : result) cout << num << endl;
return 0;
}
Using C++, we employ an unordered_map to track deadlines of whether a number is already identified as tri-consecutively occurring, which avoids duplicates and ineffective counting.