Python program to check if the list contains three consecutive common numbers in Python
Last Updated :
29 Mar, 2023
Our task is to print the element which occurs 3 consecutive times in a Python list.
Example :
Input : [4, 5, 5, 5, 3, 8]
Output : 5
Input : [1, 1, 1, 64, 23, 64, 22, 22, 22]
Output : 1, 22
Approach :
- Create a list.
- Create a loop for range size – 2.
- Check if the element is equal to the next element.
- Again check if the next element is equal to the next element.
- If both conditions are satisfied then print the element.
Example 1 : Only one occurrence of a 3 consecutively occurring element.
Python3
arr = [ 4 , 5 , 5 , 5 , 3 , 8 ]
size = len (arr)
for i in range (size - 2 ):
if arr[i] = = arr[i + 1 ] and arr[i + 1 ] = = arr[i + 2 ]:
print (arr[i])
|
Output :
5
Time Complexity: O(n)
Auxiliary Space: O(n)
Example 2 : Multiple occurrences of 3 consecutively occurring elements.
Python3
arr = [ 1 , 1 , 1 , 64 , 23 , 64 , 22 , 22 , 22 ]
size = len (arr)
for i in range (size - 2 ):
if arr[i] = = arr[i + 1 ] and arr[i + 1 ] = = arr[i + 2 ]:
print (arr[i])
|
Output :
1
22
Time Complexity: O(n*n) where n is the number of elements in the list
Auxiliary Space: O(n), where n is the number of elements in the list
Example #3: Using set() function
Python3
arr = [ 1 , 1 , 1 , 64 , 23 , 64 , 22 , 22 , 22 ]
size = len (arr)
for i in range (size - 2 ):
elements = set ([arr[i], arr[i + 1 ], arr[i + 2 ]])
if ( len (elements) = = 1 ):
print (arr[i])
|
Time Complexity: O(N)
Auxiliary Space : O(N)
Example #4:Using the itertools library:
Algorithm:
- Create a list of tuples of consecutive triplets from the input list using the zip() function.
- Use itertools.islice() to iterate over the list of triplets up to the second last element.
- Check if all three elements of the current triplet are equal.
- If they are equal, add the first element of the triplet to the output list.
- Return the output list.
Python3
import itertools
arr = [ 1 , 1 , 1 , 64 , 23 , 64 , 22 , 22 , 22 ]
triples = zip (arr, arr[ 1 :], arr[ 2 :])
print ([x for x,y,z in itertools.islice(triples, len (arr) - 2 ) if x = = y = = z])
|
Time Complexity:
Creating the list of triplets takes O(n) time, where n is the length of the input list.
The itertools.islice() function takes constant time to create an iterator over the list of triplets.
The loop over the list of triplets takes O(n) time, where n is the length of the input list.
Checking if all three elements of each triplet are equal takes constant time.
Adding an element to the output list takes constant time.
Overall, the time complexity of this code is O(n).
Auxiliary Space:
The list of triplets takes O(n) space, where n is the length of the input list.
The output list takes O(k) space, where k is the number of triplets where all three elements are equal.
Overall, the space complexity of this code is O(n + k).
Please Login to comment...