1. import heapq
  2. def sort_log_streams(log_streams, max_memory):
  3. """
  4. Sorts records of log streams for backward compatibility with limited memory usage.
  5. Args:
  6. log_streams (list of lists): A list of log streams, where each stream is a list of records.
  7. max_memory (int): The maximum number of records that can be stored in memory at once.
  8. Returns:
  9. list: A sorted list of all records from all log streams.
  10. """
  11. sorted_records = []
  12. heap = [] # Use a min-heap to track the smallest elements
  13. for stream in log_streams:
  14. for record in stream:
  15. if len(heap) < max_memory:
  16. heapq.heappush(heap, record) # Add to heap if memory allows
  17. else:
  18. if record > heap[0]: # If current record is larger than the smallest in heap
  19. heapq.heapreplace(heap, record) # Replace smallest with current record
  20. # Extract sorted records from the heap
  21. while heap:
  22. sorted_records.append(heapq.heappop(heap))
  23. return sorted_records[::-1] # Reverse to get ascending order
  24. if __name__ == '__main__':
  25. # Example usage
  26. log_streams = [
  27. [1, 5, 2, 8],
  28. [3, 7, 4, 9],
  29. [6, 10, 0, 11]
  30. ]
  31. max_memory = 5
  32. sorted_log = sort_log_streams(log_streams, max_memory)
  33. print(sorted_log)

Add your comment