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).
1using System;
2using System.Collections.Generic;
3
4class Program {
5 static List<int> FindConsecutiveNumbers(int[] nums) {
6 var result = new List<int>();
7 int count = 1;
8 for (int i = 1; i < nums.Length; i++) {
9 if (nums[i] == nums[i - 1]) {
10 count++;
11 if (count == 3 && !result.Contains(nums[i])) {
12 result.Add(nums[i]);
13 }
14 } else {
15 count = 1;
16 }
17 }
18 return result;
19 }
20
21 static void Main() {
22 int[] nums = {1, 1, 1, 2, 1, 2, 2};
23 var result = FindConsecutiveNumbers(nums);
24 foreach (var num in result) {
25 Console.WriteLine(num);
26 }
27 }
28}
29
In C#, a list is used to hold any valid numbers found during the iteration. Similar logic is applied as in other languages, keeping track of a repeated count of elements.
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.