๐ Explanation
-
import heapq
-
Imports Python’s heap queue (priority queue) library.
-
It allows you to work with heaps (a special kind of binary tree).
-
By default, heapq creates a min-heap, where the smallest element is always at the root.
-
-
nums = [40, 10, 30, 20]
-
A normal Python list with unsorted values.
-
-
heapq.heapify(nums)
-
Converts the list into a heap in-place.
-
After this, nums is rearranged internally to follow the heap property (smallest element first).
-
Now nums looks like a valid heap (but not necessarily sorted):
[10, 20, 30, 40]
-
-
heapq.nsmallest(3, nums)
-
This finds the 3 smallest elements from the heap.
-
It sorts them in ascending order before returning.
-
So, the result is:
[10, 20, 30]
-
-
print(...)
-
Prints the list of the 3 smallest numbers.
-
✅ Final Output
[10, 20, 30]


0 Comments:
Post a Comment