Python - Smallest missing element after K
Last Updated :
13 Mar, 2023
Given a List, get the smallest missing element after K in List.
Input : test_list = [1, 3, 4, 5, 7, 9, 10], K = 5
Output : 6
Explanation : After 5, 6 is 1st element missing in list.
Input : test_list = [1, 3, 4, 5, 7, 9, 11], K = 9
Output : 10
Explanation : After 9, 10 is 1st element missing in list.
Approach: Using loop
In this, we iterate through numbers and check for element missing in list, which is greater than K using conditionals.
Python3
# Python3 code to demonstrate working of
# Smallest missing element after K
# Using loop
# initializing list
test_list = [1, 3, 4, 5, 7, 9, 10]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 7
ele = 1
# infinite loop to break at element found
while(1):
# checking if greater than K and not in list
if ele > K and ele not in test_list:
res = ele
break
ele = ele + 1
# printing result
print("The Smallest element greater than K in list : " + str(res))
OutputThe original list is : [1, 3, 4, 5, 7, 9, 10]
The Smallest element greater than K in list : 8
Method #2: Using set difference
The steps of the algorithm can be described as follows:
- Create a set greater_than_K containing the range of integers between K+1 and the maximum element of the list test_list plus 1.
- Create a set missing_elements by taking the set difference between greater_than_K and the set of elements in the list test_list.
- Return the minimum element in the set missing_elements.
Python3
# Python3 code to demonstrate working of
# Smallest missing element after K
# Using set difference
def smallest_missing_element(test_list, K):
greater_than_K = set(range(K+1, max(test_list)+2))
missing_elements = greater_than_K - set(test_list)
return min(missing_elements)
# initializing list
test_list = [1, 3, 4, 5, 7, 9, 10]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 7
res=smallest_missing_element(test_list,K)
# printing result
print("The Smallest element greater than K in list : " + str(res))
#this code contributed by tvsk
OutputThe original list is : [1, 3, 4, 5, 7, 9, 10]
The Smallest element greater than K in list : 8
Time complexity: O(n), where n is the length of the input list test_list, because we need to iterate through the list to find the maximum element.
Auxiliary space: O(m), where m is the number of elements between K+1 and the maximum element of the list, because we need to create a set containing these elements. In the worst case, m can be O(n), which would make the space complexity of the algorithm O(n). However, in practice, the number of missing elements is likely to be smaller than the length of the input list, so the actual space complexity of the algorithm is likely to be smaller than O(n).
Method #3 : Using for loops
Approach
- Slice list from index of K to end of list
- Create a new list in range of K to max of list
- Now check for the element that is present in new list and not present in sliced list
- Display the element
Python3
# Python3 code to demonstrate working of
# Smallest missing element after K
# Using loop
# initializing list
test_list = [1, 3, 4, 5, 7, 9, 10]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 7
res=0
y=test_list[test_list.index(K):]
z=[]
for i in range(K,max(y)+1):
z.append(i)
for i in z:
if i not in y:
res=i
break
# printing result
print("The Smallest element greater than K in list : " + str(res))
OutputThe original list is : [1, 3, 4, 5, 7, 9, 10]
The Smallest element greater than K in list : 8
Time Complexity : O(N)
Auxiliary Space : O(N)
Method 4: using the heapq module:
First create an empty heap. Then, we loop through the elements of the input list and push any element greater than K onto the heap using heapq.heappush(). We then initialize a variable smallest to K+1 and loop through the heap using heapq.heappop(). If the popped element is not equal to smallest, we return smallest. Otherwise, we increment smallest by 1 and continue the loop. If we have processed all the elements in the heap and still haven't found a missing element, we return smallest.
Python3
import heapq
def smallest_missing_element(test_list, K):
heap = []
for x in test_list:
if x > K:
heapq.heappush(heap, x)
smallest = K + 1
while heap:
num = heapq.heappop(heap)
if num != smallest:
return smallest
smallest += 1
return smallest
# initializing list
test_list = [1, 3, 4, 5, 7, 9, 10]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 7
# calling function to get result
res = smallest_missing_element(test_list, K)
# printing result
print("The Smallest element greater than K in list : " + str(res))
OutputThe original list is : [1, 3, 4, 5, 7, 9, 10]
The Smallest element greater than K in list : 8
Time complexity: O(nlogn), where n is the number of elements in the list.
Auxiliary space: O(k), where k is the number of elements greater than K in the list.
Method #6: Using Counter and range
- Initialize a variable missing to K+1
- Initialize a counter dictionary to count the occurrence of each element in the list.
- Iterate over the range from K+1 to the maximum element in the list.
- For each number, check if it exists in the counter dictionary. If it does not, return the number as it is the smallest missing element.
- If the iteration completes without finding a missing element, return the maximum element in the list + 1.
Python3
def smallest_missing_element(test_list, K):
# Initialize missing to K+1
missing = K + 1
# Initialize a counter dictionary to count the occurrence of each element in the list
counter = {}
for num in test_list:
# If the number is greater than K, add it to the counter dictionary
if num > K:
counter[num] = counter.get(num, 0) + 1
# Iterate over the range from K+1 to the maximum element in the list
for i in range(K+1, max(test_list)+1):
# If the current number is not in the counter dictionary, it is the smallest missing element
if i not in counter:
return i
# If no missing element is found, return the maximum element in the list + 1
return max(test_list) + 1
# Driver code to test the function
test_list = [1, 3, 4, 5, 7, 9, 10]
K = 7
print("The original list is : " + str(test_list))
res = smallest_missing_element(test_list, K)
print("The Smallest element greater than K in list : " + str(res))
OutputThe original list is : [1, 3, 4, 5, 7, 9, 10]
The Smallest element greater than K in list : 8
Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(n)
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read