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.
1import
In Java, we leverage a HashMap to record numbers already recognized as appearing consecutively three times, eliminating duplication in our results.