MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / smallest_range

Function smallest_range

greedy_methods/smallest_range.py:10–65  ·  view source on GitHub ↗

Find the smallest range from each list in nums. Uses min heap for efficiency. The range includes at least one number from each list. Args: `nums`: List of k sorted integer lists. Returns: list: Smallest range as a two-element list. Examples: >>> smallest

(nums: list[list[int]])

Source from the content-addressed store, hash-verified

8
9
10def smallest_range(nums: list[list[int]]) -> list[int]:
11 """
12 Find the smallest range from each list in nums.
13
14 Uses min heap for efficiency. The range includes at least one number from each list.
15
16 Args:
17 `nums`: List of k sorted integer lists.
18
19 Returns:
20 list: Smallest range as a two-element list.
21
22 Examples:
23
24 >>> smallest_range([[4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30]])
25 [20, 24]
26 >>> smallest_range([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
27 [1, 1]
28 >>> smallest_range(((1, 2, 3), (1, 2, 3), (1, 2, 3)))
29 [1, 1]
30 >>> smallest_range(((-3, -2, -1), (0, 0, 0), (1, 2, 3)))
31 [-1, 1]
32 >>> smallest_range([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
33 [3, 7]
34 >>> smallest_range([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
35 [0, 0]
36 >>> smallest_range([[], [], []])
37 Traceback (most recent call last):
38 ...
39 IndexError: list index out of range
40 """
41
42 min_heap: list[tuple[int, int, int]] = []
43 current_max = -maxsize - 1
44
45 for i, items in enumerate(nums):
46 heappush(min_heap, (items[0], i, 0))
47 current_max = max(current_max, items[0])
48
49 # Initialize smallest_range with large integer values
50 smallest_range = [-maxsize - 1, maxsize]
51
52 while min_heap:
53 current_min, list_index, element_index = heappop(min_heap)
54
55 if current_max - current_min < smallest_range[1] - smallest_range[0]:
56 smallest_range = [current_min, current_max]
57
58 if element_index == len(nums[list_index]) - 1:
59 break
60
61 next_element = nums[list_index][element_index + 1]
62 heappush(min_heap, (next_element, list_index, element_index + 1))
63 current_max = max(current_max, next_element)
64
65 return smallest_range
66
67

Callers 1

smallest_range.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected