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).
1#include <stdio.h>
2#include <stdlib.h>
3
4void findConsecutiveNumbers(int nums[], int size) {
5 int count = 1, lastNum = nums[0];
6 for (int i = 1; i < size; i++) {
7 if (nums[i] == lastNum) {
8 count++;
9 if (count == 3) {
10 printf("%d\n", lastNum);
11 return; // Return immediately after finding the first number
12 }
13 } else {
14 count = 1;
15 lastNum = nums[i];
16 }
17 }
18}
19
20int main() {
21 int nums[] = {1, 1, 1, 2, 1, 2, 2};
22 int size = sizeof(nums) / sizeof(nums[0]);
23 findConsecutiveNumbers(nums, size);
24 return 0;
25}
26
In C, we traverse the array while maintaining a counter to track consecutive identical numbers. If the sequence reaches three and continues consecutively, the number is printed and the function terminates.
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>
2#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.