Python Program to check if elements to the left and right of the pivot are smaller or greater respectively
Last Updated :
08 Mar, 2023
Given a list and an index, the task is to write a Python program to first select the element at that index as the pivot element and then test if elements are greater to its right and smaller to its left or not.
Examples:
Input : test_list = [4, 3, 5, 6, 9, 16, 11, 10, 12], K = 4
Output : True
Explanation : Elements at Kth index is 9, elements before that are smaller and next are greater.
Input : test_list = [4, 3, 5, 6, 9, 16, 11, 10, 1], K = 4
Output : False
Explanation : Elements at Kth index is 9, elements before that are smaller but 1 is after 4th index, less than 9.
Method 1 : Using loop and enumerate()
In this, we iterate through elements using loop and enumerate is used to get indices and check if index is greater or smaller than K, to toggle testing condition.
Program:
Python3
test_list = [ 4 , 3 , 5 , 6 , 9 , 16 , 11 , 10 , 12 ]
print ( "The original list is : " + str (test_list))
K = 4
res = True
for idx, ele in enumerate (test_list):
if (idx > K and ele < test_list[K]) or (idx < K and ele > test_list[K]):
res = False
print ( "Is condition met ? : " + str (res))
|
Output:
The original list is : [4, 3, 5, 6, 9, 16, 11, 10, 12]
Is condition met ? : True
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 2 : Using all() and enumerate()
Similar task is performed using all(), which can test for required condition using single line generator expression to provide a more compact solution.
Program:
Python3
test_list = [ 4 , 3 , 5 , 6 , 9 , 16 , 11 , 10 , 12 ]
print ( "The original list is : " + str (test_list))
K = 4
res = all ( not ((idx > K and ele < test_list[K]) or (
idx < K and ele > test_list[K])) for idx, ele in enumerate (test_list))
print ( "Is condition met ? : " + str (res))
|
Output:
The original list is : [4, 3, 5, 6, 9, 16, 11, 10, 12]
Is condition met ? : True
Time complexity: O(n), where n is the length of the test_list. The all() and enumerate() takes O(n) time
Auxiliary Space: O(1), extra space required is not required
Share your thoughts in the comments
Please Login to comment...