• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
June 28, 2022 |1.7K Views
Efficient Huffman Coding for Sorted Input
  Share  1 Like
Description
Discussion

Time complexity of the algorithm discussed in above post is O(nLogn). If we know that the given array is sorted (by non-decreasing order of frequency), we can generate Huffman codes in O(n) time. Following is a O(n) algorithm for sorted input.


1. Create two empty queues.


2. Create a leaf node for each unique character and Enqueue it to the first queue in non-decreasing order of frequency. Initially second queue is empty.


3. Dequeue two nodes with the minimum frequency by examining the front of both queues. Repeat following steps two times 


       1. If second queue is empty, dequeue from first queue. 


       2. If first queue is empty, dequeue from second queue. 


       3. Else, compare the front of two queues and dequeue the minimum.  

 

Efficient Huffman Coding for Sorted Input : https://www.geeksforgeeks.org/efficient-huffman-coding-for-sorted-input-greedy-algo-4/

Read More