MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Python Example Code: Program for printing k largest elements in an array

To print the k largest elements of a Python list, you can sort it in descending order and take the first k items. That is what the example below does. For large inputs, a heap with heapq.nlargest() or a quickselect partition is faster. This tutorial explains the original code, fixes its edge-case bugs and compares the sort, heap, quickselect and NumPy approaches, with complexity notes and tests.



How the example above works

The function findKLargest sorts the list in descending order with arr.sort(reverse=True). It then loops over the first k positions and prints each value on the same line, because end=" " replaces the default newline with a space. With the sample input [1, 23, 12, 9, 30, 2, 50] and k = 3, the sorted list is [50, 30, 23, 12, 9, 2, 1], so the program prints the first three values.

$ python3 findKLargestinArray.py
50 30 23 $

The shell prompt appears right after the output because the program never prints a final newline. The stated complexity is correct: Python's sort (Timsort) is O(N log N), and printing k items adds O(k). The comment calls this "efficient", but sorting the whole list is more work than needed when k is much smaller than N. The heap and quickselect versions below avoid that extra work.

Problems with the original and a corrected version

The original code is correct for the sample input, but it has several issues that matter in real code and in interviews:

  • It mutates the caller's list. arr.sort() sorts in place, so the caller's original order is lost after the call.
  • It crashes when k is larger than the list. arr[i] raises IndexError: list index out of range when i reaches len(arr).
  • It prints instead of returning. Other code cannot reuse or test a function that only prints.
  • No trailing newline. Any output that follows ends up on the same line.
  • Naming. PEP 8 recommends snake_case for function names, so find_k_largest is the conventional spelling.
def find_k_largest(arr, k):
    """Return the k largest elements of arr in descending order.

    The input list is not modified. If k is larger than the list,
    all elements are returned. If k <= 0, an empty list is returned.
    """
    if k <= 0:
        return []
    return sorted(arr, reverse=True)[:k]


if __name__ == "__main__":
    arr = [1, 23, 12, 9, 30, 2, 50]
    k = 3
    result = find_k_largest(arr, k)
    print(*result)          # 50 30 23
    print(arr)              # [1, 23, 12, 9, 30, 2, 50] - unchangedCode language: PHP (php)

sorted() returns a new list, so the input stays unchanged. Slicing never raises IndexError: [:k] returns the whole list when k is larger than its length. print(*result) unpacks the list into separate arguments, so the values are separated by spaces and followed by a newline. The if __name__ == "__main__": guard stops the demo from running when another module imports the function.

Using heapq.nlargest from the standard library

In most production code, heapq.nlargest() is the right choice. It keeps a heap of only k items while it scans the input, so it runs in about O(N log k) time and O(k) extra memory. The result is already in descending order. It also accepts any iterable, including generators and file lines, so the data does not need to fit in a list first.

import heapq

arr = [1, 23, 12, 9, 30, 2, 50]
print(heapq.nlargest(3, arr))          # [50, 30, 23]

# Works with a key function, like sorted()
servers = [
    {"host": "web-1", "cpu": 71},
    {"host": "web-2", "cpu": 93},
    {"host": "db-1", "cpu": 88},
]
top_two = heapq.nlargest(2, servers, key=lambda s: s["cpu"])
print([s["host"] for s in top_two])    # ['web-2', 'db-1']Code language: PHP (php)

Note: The Python documentation says nlargest() works best for small values of n. When n is close to the size of the input, sorted(...)[:n] is usually faster, and for n == 1 the built-in max() is the better choice.

Writing a size-k min-heap by hand

Interviewers often ask you to implement the heap approach yourself. The idea is to keep the k largest values seen so far in a min-heap. The smallest of those k values sits at heap[0]. If a new element is larger than heap[0], it replaces the smallest one. Otherwise it cannot be among the k largest and is skipped.

import heapq

def k_largest_min_heap(arr, k):
    if k <= 0:
        return []
    heap = list(arr[:k])        # first k elements (fewer if arr is short)
    heapq.heapify(heap)         # O(k)
    for x in arr[k:]:           # remaining N - k elements
        if x > heap[0]:         # larger than the smallest of the current top k
            heapq.heapreplace(heap, x)   # pop smallest, push x: O(log k)
    return sorted(heap, reverse=True)    # O(k log k) for ordered output

print(k_largest_min_heap([1, 23, 12, 9, 30, 2, 50], 3))   # [50, 30, 23]Code language: PHP (php)

The total cost is O(k + (N โˆ’ k) log k + k log k), which is O(N log k), with O(k) extra memory. heapreplace() does the pop and the push in one operation, which is cheaper than calling heappop() and then heappush().

Quickselect for average linear time

Quickselect uses the partition step from quicksort. Pick a pivot, split the values into those greater than, equal to and less than the pivot, then recurse only into the part that still contains the k-th largest value. Its average cost is O(N). The worst case is O(Nยฒ), and a random pivot makes that case very unlikely. The three-way split below handles duplicate values correctly.

import random

def k_largest_quickselect(items, k):
    """Return the k largest elements (unordered). Average O(N)."""
    if k <= 0:
        return []
    if k >= len(items):
        return list(items)
    pivot = random.choice(items)
    greater = [x for x in items if x > pivot]
    if k <= len(greater):
        return k_largest_quickselect(greater, k)
    equal = [x for x in items if x == pivot]
    if k <= len(greater) + len(equal):
        return greater + equal[:k - len(greater)]
    less = [x for x in items if x < pivot]
    return greater + equal + k_largest_quickselect(less, k - len(greater) - len(equal))

result = k_largest_quickselect([1, 23, 12, 9, 30, 2, 50], 3)
print(sorted(result, reverse=True))   # [50, 30, 23]Code language: PHP (php)

The function returns the k largest values in no particular order. If you need them ranked, sort the result afterwards, which adds O(k log k). This list-building version is easy to read but uses O(N) extra memory. An in-place Lomuto or Hoare partition uses less memory but is more code. In pure Python, heapq.nlargest() is often just as fast in practice because its core is implemented in C. Measure before you choose.

NumPy for large numeric arrays

If the data is already in a NumPy array, use numpy.partition(). It runs a selection algorithm in compiled code and places the k largest values in the last k positions, in no guaranteed order.

import numpy as np

a = np.array([1, 23, 12, 9, 30, 2, 50])
k = 3
top_k = np.partition(a, -k)[-k:]        # k largest, unordered
print(np.sort(top_k)[::-1])             # [50 30 23]

# Indices instead of values
idx = np.argpartition(a, -k)[-k:]
print(idx[np.argsort(a[idx])[::-1]])    # [6 4 1]Code language: PHP (php)

Note: np.partition(a, -k) raises a ValueError if k is larger than the array length, so check the bounds first. Converting a Python list to an array costs O(N), so NumPy only pays off when the data is already an array or is large.

Choosing an approach

ApproachTimeExtra spaceOutput orderBest for
sorted(arr, reverse=True)[:k]O(N log N)O(N)DescendingSimple code, or k close to N
heapq.nlargest(k, arr)O(N log k)O(k)DescendingDefault choice, streams, small k
Manual min-heapO(N log k)O(k)Descending after final sortInterviews, custom logic
QuickselectO(N) average, O(Nยฒ) worstO(N) as writtenUnorderedVery large N when only membership matters
numpy.partitionO(N) on averageO(N)UnorderedNumeric data already in NumPy

Relative speed depends on N, k, your data and your Python version. To compare approaches on your own data, use timeit:

python3 -m timeit -s "import random, heapq; a=[random.random() for _ in range(1_000_000)]" "heapq.nlargest(10, a)"
python3 -m timeit -s "import random; a=[random.random() for _ in range(1_000_000)]" "sorted(a, reverse=True)[:10]"Code language: JavaScript (javascript)

Testing edge cases and common errors

Each implementation should pass the same set of edge cases. These assertions work with find_k_largest, and with the other functions after you sort their output:

def test_find_k_largest():
    assert find_k_largest([1, 23, 12, 9, 30, 2, 50], 3) == [50, 30, 23]
    assert find_k_largest([5, 1, 5, 3], 2) == [5, 5]        # duplicates kept
    assert find_k_largest([4, 2], 10) == [4, 2]              # k > len
    assert find_k_largest([4, 2], 0) == []                   # k == 0
    assert find_k_largest([], 3) == []                       # empty input
    assert find_k_largest([-3, -1, -2], 1) == [-1]           # negatives

test_find_k_largest()
print("all tests passed")Code language: PHP (php)
  • IndexError: list index out of range: this is the original loop with k > len(arr). Use slicing or min(k, len(arr)).
  • Wrong order with input from input(): values read as strings sort alphabetically, so "9" ranks above "50". Convert them first with arr = list(map(int, input().split())).
  • TypeError: '<' not supported between instances of 'str' and 'int': Python 3 cannot compare mixed types. Clean the data or pass a key function.
  • Duplicates in the result: [5, 5] counts as two of the largest elements. If you need distinct values, deduplicate first with heapq.nlargest(k, set(arr)).

Frequently asked questions

What is the fastest way to get the k largest elements in Python?

In most cases, use heapq.nlargest(k, data), which runs in about O(N log k) and keeps only k items in memory. When k is close to N, sorted(data, reverse=True)[:k] is usually faster. For numeric NumPy arrays, np.partition is the fastest option.

How do I find the k largest elements without changing the original list?

Use sorted() or heapq.nlargest(). Both return a new list. list.sort() sorts the list in place and destroys the original order, which is what the example above does.

Is a min-heap or a max-heap used for the k largest elements?

Use a min-heap of size k. Its root is the smallest of the current top k, so each new element needs only one comparison with heap[0]. A max-heap of all N elements also works, but it uses O(N) memory.

How do I get the indices of the k largest elements?

For a list, use heapq.nlargest(k, range(len(arr)), key=arr.__getitem__). For a NumPy array, use np.argpartition(a, -k)[-k:] and then sort those indices by their values if you need them ranked.

What is the time complexity of the original sorting approach?

It is O(N log N) for the sort plus O(k) for printing, which is O(N log N) overall. It also needs no extra memory beyond the in-place sort, but it modifies the input list.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Python Example Code: Find the pair of adjacent elements that has the largest product

Rajesh Kumar I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have…

Read More

Python Example Code: Find all the pairs of numbers which sum upto `k`

This page shows how to find every pair of numbers in a Python list that adds up to a target value k, a common coding-interview question. The…

Read More

Top 10 AI Ride-Hailing Matching Algorithms Tools: Features, Pros, Cons & Comparison

Introduction AI Ride-Hailing Matching Algorithms use artificial intelligence, machine learning, predictive analytics, and optimization techniques to connect passengers with suitable drivers efficiently. These systems analyze multiple real-time…

Read More

Principal Quantum Algorithm Scientist: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path

The **Principal Quantum Algorithm Scientist** is a senior individual-contributor (IC) scientist who invents, adapts, and validates quantum algorithms that can be delivered through a software product or IT platform (typically a cloud-based quantum computing service, SDK, or enterprise solution). The role bridges foundational research and production-grade enablement by turning algorithmic ideas into reproducible code, benchmarks, and developer-ready artifacts that product and engineering teams can ship and support.

Read More

Lead Quantum Research Scientist: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path

The **Lead Quantum Research Scientist** is a senior, research-heavy individual contributor (IC) who sets the technical direction for quantum algorithms and applied quantum research that can be translated into software products, developer tools, or client-facing solutions. This role bridges **foundational research** (quantum information science, algorithm design, error models) with **engineering execution** (prototype code, benchmarks, integration into quantum software stacks).

Read More

Lead Quantum Algorithm Scientist: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path

The **Lead Quantum Algorithm Scientist** is a senior individual-contributor scientist who designs, proves, prototypes, and operationalizes quantum algorithms and resource-estimation methods that can be delivered through a software or IT organizationโ€™s quantum computing platform, developer tools, or applied solutions portfolio. This role bridges rigorous research (algorithm design, complexity, error models) with production-minded engineering (reproducible code, benchmarking, integration into SDKs, and customer-facing enablement).

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x