Write Python Program to find the Kth Smallest Element29 Aug 2024 | 5 min read The problem is a given an integer array, we need to find the kth smallest element in the array where k is a positive integer less than or equal to the length of the array. Let's see the following example. Example - Input: Output: k'th smallest array element is 4 Input: Output: k'th smallest array element is 10 Let's solve this problem using the various methods. Method - 1: Brute Force ApproachIn this approach, first, we will sort the given array. Here we will use the bubble sort algorithm and gets the Kth smallest element using list slicing. Let's understand the following example. Example - Output: kth smallest array element is: 7 Explanation - In the above function, we define a function called find_k_smallest() that finds the k-th smallest element in an array using a simple sorting approach.
In the given example, the input array is [7, 10, 4, 3, 20, 15], and the desired k-th smallest element is the 3rd smallest (k = 3). After running the find_k_smallest() function, the output will be 7, which is the 3rd smallest element in the sorted array. Hence this implementation has a time complexity of O(n2) because of the nested loops used for sorting. However, we will optimize the above solution. Method - 2 Using Sort MethodWe will use the built-in sort() method. Let's understand the following example. Example - Output: kth smallest array element is: 7 Explanation - The function find_k_smallest() takes three parameters: arr (the input array), n (the length of the array), and k (the position of the desired k-th smallest element). We use the sort() method to sort the array in ascending order. This rearranges the elements of the array such that the smallest element is at index 0 and the largest element is at the last index. After sorting the array, the function returns the element at index k-1. Since array indexing starts from 0, the k-th smallest element will be at index k-1. The overall time complexity of the above code is O(n log n), where n is the length of the array. Method - 3: Using Max HeapWe will solve this problem using the min heap. Let's understand the following example. Example - Output: kth smallest array element is:7 Explanation - In the above code, we import the heapq module, to work with the heap. Then, we create the empty heap to store the elements of the array. After pushing all elements onto the heap, we enter a loop to extract the smallest element k times. We use heapq.heappop() to pop and retrieve the smallest element from the heap. The kth_smallest variable keeps track of the k-th smallest element as we extract elements from the heap. Finally, we return the value of kth_smallest, which will be the k-th smallest element in the array. The time complexity of the above code is O(n) which is an optimized version of previous codes. Method - 4: Using Priority QueueTo solve the problem of finding the k-th smallest element using a priority queue, we can utilize Python's queue module, specifically the PriorityQueue class. Here's an implementation using a priority queue. Let's understand the following example. Example - Output: kth smallest array element is: 7 Explanation - In the above code, first we import the PriorityQueue class from the queue module, which allows us to work with a priority queue. The find_k_smallest function takes two parameters: arr (the input array) and k (the position of the desired k-th smallest element). We create a new pq instance of the PriorityQueue class. We iterate over each element in the array and use the put() method to insert the element into the priority queue. After inserting an element, we check if the size of the priority queue (pq.qsize()) is greater than k. If it is, we remove the smallest element from the priority queue using the get() method. This ensures that the priority queue only contains the k smallest elements at any given time. After processing all elements, we use the get() method to retrieve the k-th smallest element from the priority queue. Finally, we return the retrieved k-th smallest element. |
Generally, prototypes or real-life Internet of Things (IoT) systems have to be designed and developed swiftly and competently. Whenever this occurs, two activities instantly come to life: One is to program the IoT devices, and another is to organize a backend to interact with these devices. In...
9 min read
Bokeh is an Interactive Data visualization library of Python. It creates its plots by using HTML and JavaScript languages. Its basic targets are modern website browsers for presenting provided elegance, concise construction of novel graphics with high-performance interactivity. In this tutorial, we will learn how to create...
3 min read
Python automated testing can be done with the Selenium Python Module. The Selenium Python bindings provide a straightforward API for writing functional and acceptability tests with Selenium WebDriver. Visit Navigating links using the get method - Selenium Python to learn how to open a website using...
2 min read
In this tutorial, we will see how we can create a dictionary inside a list and then what are the operations that we can perform. So let's start with creating a dictionary inside a list. Consider the program given below, #initialising a dictionary inside a list list_val=[{'English':31101,'Hindi':31102,'Mathematics':31103,'Physics':31104,'Chemistry':31105}] #displaying the list print("The dictionary...
3 min read
PyGTK is a Python binding for the GTK+ (GIMP Toolkit) graphical user interface library. It provides a powerful and flexible set of tools for creating cross-platform graphical user interfaces (GUIs) for desktop applications. In this article, we will explore the features of PyGTK and how to...
5 min read
Apache Spark is a popular distributed computing framework for big data processing that offers a rich set of APIs for working with structured data. Spark provides a powerful way to work with data using data frames, which are like tables in a relational database. One of...
7 min read
Pandas Pandas is an inbuilt library in Python which is used to work with relational data in the Python programming language. It has a lot of functions and data structures which help in the operations of relational data. If the data is stored in the form of rows...
4 min read
Introduction In Python, a private method is a method that is not intended to be used outside of the class in which it is defined. These methods are denoted by a double underscore prefix (__) before their name, and they can only be accessed within the class...
3 min read
Loops are a very helpful, time-saving and efficient at the same time. Using loops is our first choice if we want to automate and repeat a task. But, sometimes, we get into a situation where We have to terminate the loop if a particular condition becomes true. We...
4 min read
In this tutorial, we will learn the fundamentals of the standard logging module. What is logging? Logging is a Python module in the standard library that provides the facility to work with the framework for releasing log messages from the Python programs. Logging is used to tracking events...
9 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India