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).
1def find_consecutive_numbers(nums):
2 result = []
3 count = 1
4 for i in range(1, len(nums)):
5 if nums[i] == nums[i-1]:
6 count += 1
7 if count == 3 and (not result or result[-1] != nums[i]):
8 result.append(nums[i])
9 else:
10 count = 1
11 return result
12
13nums = [1, 1, 1, 2, 1, 2, 2]
14print(find_consecutive_numbers(nums))
15
Python's version is simple and utilizes a list to track any numbers that are tri-consecutive in the sequence. The variable 'count' tracks the current streak of identical numbers.
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.