⬅ Previous Topic
Max Consecutive Ones in ArrayNext Topic ⮕
Longest Subarray with Given Sum (Positives)⬅ Previous Topic
Max Consecutive Ones in ArrayNext Topic ⮕
Longest Subarray with Given Sum (Positives)Topic Contents
Given an unsorted array of integers and a number k
, your task is to find the kth smallest element in the array using an efficient technique.
k
is 1-based, meaning k = 1
refers to the smallest element, k = 2
refers to the second smallest, and so on.k
is larger than the number of elements in the array, return -1
or indicate that it is out of bounds.This problem can be solved in linear average time using the Quickselect algorithm, which is related to Quicksort but optimized to find a specific order statistic without full sorting.
k
(1-indexed), the goal is to find the kth smallest element.lows
(elements less than the pivot), pivots
(elements equal to the pivot), and highs
(elements greater than the pivot).k
is less than or equal to the size of lows
, recursively search in lows
.k
is within the size of lows
plus pivots
, the pivot is the kth smallest element.highs
with an updated k
(subtracting the sizes of lows
and pivots
).import random
def quickselect(arr, k):
if len(arr) == 1:
return arr[0]
pivot = random.choice(arr)
lows = [x for x in arr if x < pivot]
highs = [x for x in arr if x > pivot]
pivots = [x for x in arr if x == pivot]
if k <= len(lows):
return quickselect(lows, k)
elif k <= len(lows) + len(pivots):
return pivot
else:
return quickselect(highs, k - len(lows) - len(pivots))
if __name__ == '__main__':
arr = [7, 10, 4, 3, 20, 15]
k = 3
print("The", k, "th smallest element is:", quickselect(arr, k))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | If the pivot divides the array evenly, each recursive call reduces the problem size by half, leading to linear time complexity. |
Average Case | O(n) | On average, the random pivot leads to a fairly balanced partition, resulting in linear time complexity for finding the kth element. |
Average Case | O(n²) | In the worst case (e.g., when the smallest or largest element is always chosen as pivot), the partitioning is highly unbalanced, resulting in quadratic time complexity. |
O(1) (in-place) or O(n) (with extra arrays)
Explanation: If implemented in-place like Lomuto partition, it uses constant space. But if implemented with extra arrays for lows, pivots, and highs, it uses linear space.
⬅ Previous Topic
Max Consecutive Ones in ArrayNext Topic ⮕
Longest Subarray with Given Sum (Positives)You can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.