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#
In C, we use an auxiliary array to mimic a hashmap for counting occurrences of numbers. We focus on consecutive occurrences rather than entire counts, thus determining which numbers are consecutive.