Open In App

Python – Nth smallest Greater than K

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This article offers various approaches to solve the problem of finding Nth smallest number in python list greater than a specific element K in python list. This basically provides all the approaches from naive to one-liners so that they can be used in programming whenever required.

Method 1 : Naive Method + sort()

Using loop we keep on adding elements that are greater than K and then sort the list and find the Nth element greater than K. 

Python3




# Python 3 code to demonstrate
# Nth smallest Greater than K
# using naive method + sort()
 
# Initializing list
test_list = [1, 4, 7, 5, 10]
 
# Initializing k
k = 6
 
# Initializing N
N = 2
 
# Printing original list
print ("The original list is : " + str(test_list))
 
# Using naive method + sort()
# Nth smallest Greater than K
res = []
for i in test_list :
    if i > k :
        res.append(i)
res.sort()
 
# Printing result
print ("The Nth minimum value greater than 6 is : " + str(res[N - 1]))


Output : 

The original list is : [1, 4, 7, 5, 10]
The Kth minimum value greater than 6 is : 10

Time Complexity: O(nlogn), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space required

Method 2: lambda + filter() + sort() 

A similar approach to the method above, just to filter the numbers in a list greater than k, filter() instead of the loop is used in this approach. Works in a similar way as above after that. 

Python3




# Python 3 code to demonstrate
# Nth smallest Greater than K
# using min() + sort() + lambda
 
# Initializing list
test_list = [1, 4, 7, 5, 10]
 
# Initializing k
k = 6
 
# Initializing N
N = 2
 
# Printing original list
print ("The original list is : " + str(test_list))
 
# Nth smallest Greater than K
# using min() + sort() + lambda
res = list(filter(lambda i: i > k, test_list))
res.sort()
 
# Printing result
print ("The Nth minimum value greater than 6 is : " + str(res[N - 1]))


Output : 

The original list is : [1, 4, 7, 5, 10]
The Kth minimum value greater than 6 is : 10

Time complexity: O(nlogn), where n is the length of the input list. This is because the code uses the sort() function, which has a time complexity of O(nlogn).
Auxiliary space: O(n), where n is the length of the input list. This is because the code creates a new list (res) to store the filtered values that are greater than k, and the size of the new list can be at most n.

Method 3 : Here’s an approach using heapq.nsmallest():

Python3




import heapq
 
test_list = [1, 4, 7, 5, 10]
k = 6
N = 2
 
res = heapq.nsmallest(N, filter(lambda i: i > k, test_list))
print("The Nth minimum value greater than 6 is :", res[-1])
#This code is contributed by Edula Vinay Kumar Reddy


Output

The Nth minimum value greater than 6 is : 10

Time complexity: O(N * log(N)), where N is the number of elements in the filtered list.
Auxiliary Space: O(N) for storing the filtered list and the result list.

This approach takes advantage of the built-in heapq module to find the N largest elements in the filtered list in O(N * log(N)) time. This is faster than sorting the filtered list and accessing the Nth element, which would take O(N * log(N)) time for sorting and O(1) time for accessing the Nth element, for a total of O(N * log(N)) time.

Method#4: Using the Recursive method

Algorithm:

1. Define a function called nth_smallest_greater_than_k that takes a list (lst), a value (K), and an integer (N) as input.
2. Check if the list is empty. If it is, return None.
3. Recursive case: divide the list into two sublists: elements greater than K and elements less than or equal to K.
4. Check if the length of the greater sublist is greater than or equal to N. If it is, sort the greater sublist and return the Nth smallest value.
5. Recursive case: subtract the length of the greater sublist from N and recursively call the function on the less or equal sublist with the updated value of N.
6. When the recursive call returns, the function will have found the Nth smallest value greater than K.
7. Return the Nth smallest value greater than K.

Python3




def nth_smallest_greater_than_k(lst, k, N):
    # base case: empty list
    if not lst:
        return None
     
    # recursive case: split list into elements greater than K and elements less than or equal to K
    greater = [x for x in lst if x > k]
    less_or_equal = [x for x in lst if x <= k]
     
    # recursive case: Nth smallest greater than K is in the greater list
    if len(greater) >= N:
        greater_sorted = sorted(greater)
        return greater_sorted[N-1]
     
    # recursive case: Nth smallest greater than K is in the less or equal list
    else:
        next_N = N - len(greater)
        return nth_smallest_greater_than_k(less_or_equal, k, next_N)
test_list = [1, 4, 7, 5, 10]
k = 6
N = 2
res=nth_smallest_greater_than_k(test_list, k, N)
print("The Nth minimum value greater than 6 is :", res)


Output

The Nth minimum value greater than 6 is : 10

The time complexity of the function is O(n log n), where n is the length of the input list, because the function uses the built-in sorted() function to sort the greater sublist at each recursive call.

The space complexity of the function is O(n), because the function creates new lists at each recursive call. However, the maximum depth of recursion is bounded by the length of the input list, so the space usage is also O(n) in the worst case.

METHOD 5:Using defaultdict

This program finds the Nth smallest element greater than K in a given list of integers using a defaultdict from the collections module.

Algorithm:

1.Initialize an empty defaultdict to count the occurrences of elements greater than K in the list.
2.Iterate over the elements of the list and increment the count for each element greater than K in the defaultdict.
3.Sort the keys of the defaultdict in ascending order.
4.Retrieve the Nth element from the sorted keys.
5.Print the result to the console.

Python3




from collections import defaultdict
 
lst = [1, 4, 7, 5, 10]
K = 6
N = 2
 
# create a defaultdict to count elements greater than K
greater_than_k = defaultdict(int)
for x in lst:
    if x > K:
        greater_than_k[x] += 1
 
# get the Nth smallest element
result = sorted(greater_than_k.keys())[N-1]
 
print("The Kth minimum value greater than", K, "is :", result)


Output

The Kth minimum value greater than 6 is : 10

Time Complexity: O(n log n) because of the sort operation on the keys of the defaultdict.
Auxiliary Space: O(n) because we create a defaultdict to store the counts of each element greater than K in the list.

Method 6: using Heep

Step-by-step algorithm for the heapq approach to find the Nth smallest value greater than K:

  1. Import the heapq module.
  2. Initialize the input list test_list, K and N.
  3. Initialize an empty heap list.
  4. Traverse the elements of the input list test_list.
  5. Check if the element is greater than K or not.
  6. If the element is greater than K, push it to the heap list using heapq.heappush().
  7. After all the elements of the input list have been traversed, use heapq.nsmallest() to get the N smallest elements from the heap list.
  8. Since we need the Nth smallest value greater than K, return the (N-1)th element of the N smallest elements obtained from the heap list.
  9. Print the Nth smallest value greater than K.

Python3




import heapq
 
# Initializing list
test_list = [1, 4, 7, 5, 10]
 
# Initializing k
k = 6
 
# Initializing N
N = 2
 
# Printing original list
print("The original list is:", test_list)
 
# Using heapq module
# Find the Nth smallest value greater than k
heap = []
for x in test_list:
    # check if element is greater than k, if it is, then push it to heap
    if x > k:
        heapq.heappush(heap, x)
 
# get the Nth smallest element from the heap
res = heapq.nsmallest(N, heap)[-1]
 
# Printing result
print("The Nth minimum value greater than {} is: {}".format(k, res))


Output

The original list is: [1, 4, 7, 5, 10]
The Nth minimum value greater than 6 is: 10

Time complexity: The time complexity of building the heap is O(NlogN), where N is the number of elements greater than K in the input list. The time complexity of obtaining the N smallest elements from the heap is O(NlogK), where K is the number of elements in the heap list. Since K is generally smaller than N, the overall time complexity of the algorithm is O(NlogN).

Auxiliary space complexity: The auxiliary space complexity of the algorithm is O(N), where N is the number of elements greater than K in the input list. This is because we need to store all the elements greater than K in the heap list.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads