You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在HackerRank用Python实现堆数据结构时如何避免运行时错误?

Fixing Runtime Errors in Your HackerRank Heap Implementation

Let's walk through the issues in your current code and adjust it to avoid runtime errors while handling the heap operations correctly.

Key Issues in Your Current Code

  • Unchecked heap[0] access: When you try to check heap[0] for operation 2, if the heap is empty, this will throw an IndexError immediately—one of the most common runtime errors here.
  • Incomplete deleted node handling: Your code cuts off mid-way through cleaning up deleted elements, which means stale (already marked for deletion) elements might linger at the heap top, leading to wrong results or errors when you try to access them.
  • Inefficient deletion tracking: Using a separate heap for deleted nodes makes it hard to handle duplicate values properly and syncs poorly with the main heap.

Improved Implementation with Error Prevention

Instead of tracking deleted nodes in a separate heap, use a dictionary to count how many times each value needs to be deleted. This lets us lazily clean up the heap only when we need to access the top element (which is when operations 2 checks the top or operation 3 requests the minimum).

Here's the revised code:

from heapq import heappush, heappop
from collections import defaultdict

heap = []
delete_counts = defaultdict(int)
num_of_entries = int(input())

for _ in range(num_of_entries):
    line = list(map(int, input().strip().split()))
    if line[0] == 1:
        # Push element to heap
        heappush(heap, line[1])
    elif line[0] == 2:
        # Increment delete count for the target value
        delete_counts[line[1]] += 1
    elif line[0] == 3:
        # Clean up stale elements from heap top first
        while heap:
            top = heap[0]
            if delete_counts[top] > 0:
                delete_counts[top] -= 1
                if delete_counts[top] == 0:
                    del delete_counts[top]
                heappop(heap)
            else:
                break
        # Now the top is valid, print it
        print(heap[0])

Why This Fixes Runtime Errors

  1. No more empty heap index access: Before accessing heap[0] in operation 3, we first check if the heap is non-empty and clean up any stale elements. (HackerRank test cases typically guarantee valid operations, but you could add a guard clause here if needed.)
  2. Lazy cleanup: We only clean up the heap when necessary, which avoids unnecessary operations and ensures we never work with stale elements.
  3. Robust duplicate handling: Using a count dictionary lets us track multiple deletions of the same value without getting confused by duplicates in the heap.

Additional Notes for Your Original Approach

If you wanted to stick with the deleted_nodes heap approach, you'd need to:

  • Always clean up the heap top before any operation that accesses it (operations 2 and 3)
  • Check if the heap is empty before trying to access heap[0]
  • Handle cases where the deleted node is present multiple times in both heaps

But the count dictionary method is far more efficient and less error-prone for this type of problem.

内容的提问来源于stack exchange,提问作者Mohamed Saad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:15:19