Huffman Encoding | Practice | GeeksforGeeks

Given a string S of distinct character of size N and their corresponding frequency f[ ] i.e. character S[i] has f[i] frequency. Your task is to build the Huffman tree print all the huffman codes in preorder traversal of the tree.
Note: While merging if two nodes have the same value, then the node which occurs at first will be taken on the left of Binary Tree and the other one to the right, otherwise Node with less value will be taken on the left of the subtree and other one to the right.
Example 1:
S = "abcdef"
f[] = {5, 9, 12, 13, 16, 45}
Output: 
0 100 101 1100 1101 111
Explanation:

HuffmanCodes will be:
f : 0
c : 100
d : 101
a : 1100
b : 1101
e : 111
Hence printing them in the PreOrder of Binary 
Tree.
Your Task:
You don't need to read or print anything. Your task is to complete the function huffmanCodes() which takes the given string S, frequency array f[ ] and number of characters N as input parameters and returns a vector of strings containing all huffman codes in order of preorder traversal of the tree.
Expected Time complexity: O(N * LogN) 
Expected Space complexity: O(N) 
Constraints:
1 ≤ N ≤ 26
0
msandhiya82483 days ago
C++ CLEAN SOLUTION:
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;

 // } Driver Code Ends
class Solution
{
    public:
	
	   struct Node{
	     char dat;
	     int freq;
	    
	     Node *left,*right;
	   };
	  Node * newNode(char j,int f){
	      Node *n=new Node();
	      n->dat=j;
	      n->freq=f;
	      n->left=NULL;
	      n->right=NULL;
	  }
	    struct cmpare{
	      bool operator()(Node *l,Node *r){
	          return l->freq>r->freq;
	      }  
	    };
	   
	    void preorder(Node *r,string t,vector<string>&a ){
	        if(r->left==NULL and r->right==NULL)
	        {
	            a.push_back(t);
	            return;
	        }
	        preorder(r->left,t+'0',a);
	        preorder(r->right,t+'1',a);
	        
	    }
	    
	    
		vector<string> huffmanCodes(string S,vector<int> f,int N)
		{
		    Node *root=NULL;
		    priority_queue<Node *,vector<Node *>,cmpare>p;
		    for(int i=0;i<N;i++){
		        Node *t=newNode(S[i],f[i]);
		        p.push(t);
		    }
		    vector<string>v;
		    while(p.size()>1){
		        Node *n;
		        Node *l=p.top();
		        p.pop();
		        Node *r=p.top();
		        p.pop();
		        
		       // cout<<l->freq<<"  "<<r->freq<<endl;
		        n=newNode('*',l->freq+r->freq);
		        if(l->freq<=r->freq){
		            n->left=l;
		            n->right=r;
		        }
		        else{
		            n->left=r;
		            n->right=l;
		        }
		      //cout<<n->freq<<" ";
		        p.push(n);
		       
		        
		    }
		    root=p.top();
		 //   cout<<root->freq;
		    string s;
		     preorder(root,s,v);
		   
		    return v;
		    
		}
};

// { Driver Code Starts.
int main(){
    int T;
    cin >> T;
    while(T--)
    {
	    string S;
	    cin >> S;
	    int N = S.length();
	    vector<int> f(N);
	    for(int i=0;i<N;i++){
	        cin>>f[i];
	    }
	    Solution ob;
	    vector<string> ans = ob.huffmanCodes(S,f,N);
	    for(auto i: ans)
	    	cout << i << " ";
	    cout << "\n";
    }
	return 0;
}  // } Driver Code Ends
+1
arkoghoshdastidar3920005 days ago
C++ solution:
Time Complexity : O(nlogn)
Space Complexity : O(n)
 
Concepts used :  Tree traversal & min_priority_queue.
 
Solution : 
class Node{
    public:
    char data;
    int frequency;
    Node* left;
    Node* right;
    Node(){
        this->left = NULL;
        this->right = NULL;
        this->data = '*';
    }
    Node(int frequency){
        this->frequency = frequency;
        this->data = '*';
        this->left = NULL;
        this->right = NULL;
    }
    Node(char data, int frequency){
        this->data = data;
        this->frequency = frequency;
        this->left = NULL;
        this->right = NULL;
    }
};

class cmp{
  public:
  bool operator()(Node* n1, Node* n2){
      return n1->frequency > n2->frequency;
  }  
};

vector<Node*> pairCharWithFrequency(string S, vector<int> f, int N){
    vector<Node*> characterAndFrequencyPair;
    for(int i=0; i<N; i++){
        Node* currentNode = new Node(S[i], f[i]);
        characterAndFrequencyPair.push_back(currentNode);
    }
    return characterAndFrequencyPair;
}

void insertNodesInPQ(vector<Node*> characterAndFrequencyPair, priority_queue<Node*, vector<Node*>, cmp> &pq, int N){
    for(int i=0; i<N; i++){
        pq.push(characterAndFrequencyPair[i]);
    }
}

Node* setHuffmanTree(priority_queue<Node*, vector<Node*>, cmp> &pq){
    Node* rootNode = NULL;
    while(pq.size() > 1){
        Node* n1 = pq.top();
        pq.pop();
        Node* n2 = pq.top();
        pq.pop();
        Node* newNode = new Node(n1->frequency+n2->frequency);
        if(n1->frequency <= n2->frequency){
            newNode->left = n1;
            newNode->right = n2;
        }else{
            newNode->right = n1;
            newNode->left = n2;
        }
        pq.push(newNode);
    }
    rootNode = pq.top();
    return rootNode;
}

void getCodes(Node* node, string code, vector<string> &codes){
    if(!node->left && !node->right){
        codes.push_back(code);
        return;
    }
    getCodes(node->left, code+'0', codes);
    getCodes(node->right, code+'1', codes);
}

class Solution{
    public:
	vector<string> huffmanCodes(string S,vector<int> f,int N){
	   vector<string> codes;
	   string s;
	   if(N == 1){
	       //Only one character present in the string S.
	       return codes;
	   }
	   vector<Node*> characterAndFrequencyPair = pairCharWithFrequency(S, f, N);  //O(n)
	   priority_queue<Node*, vector<Node*>, cmp> pq;   
	   insertNodesInPQ(characterAndFrequencyPair, pq, N);  //O(nlogn)
	   Node* rootNode = setHuffmanTree(pq);  //O(nlogn)
	   getCodes(rootNode, s, codes);  //O(n)
	   return codes;
	}
};
0
avinashdhn19042 weeks ago
// C++ code using priority_queue

class Node{
  public:
  int data;
  Node *left,*right;
  Node(int x){
      this->data=x;
      this->left=NULL;
      this->right=NULL;
  }
};
struct cmp{
    bool operator()(Node *l,Node *r){
        return (l->data>r->data);
    }
};
class Solution
{
	public:

void preorder(Node *root,string s,vector<string>&ans){
    if(root==NULL)return;
    if(root->left==NULL&&root->right==NULL){
        ans.push_back(s);
    }
    preorder(root->left,s+'0',ans);
    preorder(root->right,s+'1',ans);
}
		vector<string> huffmanCodes(string S,vector<int> f,int N)
		{
		   vector<string>ans;
		   priority_queue<Node*,vector<Node*>,cmp>mh;
		   for(int i=0;i<N;i++){
		       Node *root=new Node(f[i]);
		       mh.push(root);
		   }
		   while(mh.size()!=1){
		       Node *left=mh.top();
		       mh.pop();
		       Node *right=mh.top();
		       mh.pop();
		       Node *parent= new Node(left->data+right->data);
		       parent->left=left;
		       parent->right=right;
		       mh.push(parent);
		   }
		   Node *root=mh.top();
		   mh.pop();
		   preorder(root,"",ans);
		   return ans;
		}
};

0
dheerukd20022 weeks ago
class Node{
    public:
    char data;
    int val;
    Node* left;
    Node* right;
    
    Node(int i,char c='#'){
        val=i;
        data=c;
        left=NULL;
        right=NULL;
    }
};

void decodeHuff(Node* root,string s,vector<string> &v){
    if(!root)return;
    
    if(root->left==NULL&&root->right==NULL){
        v.push_back(s);
        return ;
    }
    
    decodeHuff(root->left,s+"0",v);
    decodeHuff(root->right,s+"1",v);
    
}

bool comp(Node*n1,Node*n2){
    return n1->val>n2->val;
}

class Solution
{
	public:
		vector<string> huffmanCodes(string S,vector<int> f,int N){
		    
		    if(N==1)return {0};
		    
		    priority_queue<Node*,vector<Node*>,function<bool(Node*,Node*)>>pq(comp);
		    
		    for(int i=0;i<N;i++){
		        Node* n=new Node(f[i],S[i]);
		        pq.push(n);
		    }
		    
		    while(pq.size()!=1){
		        Node* t1=pq.top();
		        pq.pop();
		        Node* t2=pq.top();
		        pq.pop();
		        
		        Node* n=new Node(t1->val+t2->val);
		        
		        n->left=(t1->val<=t2->val)?t1:t2;
		        n->right=(t1->val<=t2->val)?t2:t1;
		        
		        pq.push(n);
		    }
		    
		    vector<string> ans;
		    
		    decodeHuff(pq.top(),"",ans);

		    return ans;
		    
		}
};
+2
billagreeshman3 weeks ago
 
struct data{
        int val;
        vector<string> s;
    };


class cmp
{
    public:
    int operator()(const data a,const data b){
        return a.val>b.val;
    }
};
class Solution
{

    
	public:
		vector<string> huffmanCodes(string s,vector<int> f,int n)
		{
		    // Code here
		    priority_queue<data,vector<data>,cmp> heap;
		    
		    for(int i=0;i<n;i++){
		        
		        data temp;
		        temp.val=f[i];
		        temp.s=vector<string>(1,"");
		        
		        heap.push(temp);
		    }
		    
		    while(heap.size()>1){
		        int f1=heap.top().val;
		        vector<string> f2=heap.top().s;
		        heap.pop();
		        
		        int s1=heap.top().val;
		        vector<string> s2=heap.top().s;
		        heap.pop();
		        
		        for(int i=0;i<f2.size();i++){
		            f2[i]="0"+f2[i];
		        }
		        for(int i=0;i<s2.size();i++){
		            s2[i]="1"+s2[i];
		        }
		        f1+=s1;
		        data temp;
		        temp.val=f1;
		        temp.s=f2;
		        temp.s.insert(temp.s.end(),s2.begin(),s2.end());
		        heap.push(temp);
		    }
		    vector<string> ans=heap.top().s;
		    
		    
		    return heap.top().s;
		}
};
0
xxxcoder_fnc4 weeks ago
please anybody check why it's not working
 
 
class Node{  public:  char data;  int freq;  Node* left;  Node*right;    Node(char data,int freq){      this->data=data;      this->freq=freq;      left=right=NULL;  }};
//for priority queue
class compare{   bool operator()(Node*a,Node*b){       return (a->freq > b->freq);   }   };
void print_code(Node *root,string a,vector<string>&ans){     if(root==NULL){return;}          //we have already initiallize the sum data with '&'     //now any node we encounter having '&' we do'nt accept     //node not containing '&' will be our input node only     if(root->data!='&'){        ans.push_back(a);      }     print_code(root->left,a+"0",ans);//go left add 0     print_code(root->right,a+"1",ans);//go right add 1      } vector<string> huffmanCodes(string S,vector<int> f,int N) {   // Node *l,*r,*top;   //we are creating a min heap   //so that only top minimum two will be always get added    priority_queue<Node*,vector<Node*>,compare>pq;    for(int i=0;i<f.size();i++){       pq.push(new Node(S[i],f[i]));     }    //now we have to compute sum till we get last node    while(pq.size()!=1){      //extract the two minimum and add it and make three internal nodes     Node *left=pq.top();    pq.pop();       Node *right=pq.top();    pq.pop();        //create new internal node    Node* top=new Node('&',left->data+right->data);    top->left=left;    top->right=right;        //now insert the top in the queue    pq.push(top);            }    //now we have to print/insert the hoffman code    //in the vector     vector<string>ans;    print_code(pq.top(),"",ans);    return ans; }
 
+4
roboto7o32oo31 month ago
Clean C++ Solution✨✨
 
class Solution
{
	public:
	
	    struct Node{
	        string symbol;
	        int frequency;
	        Node* left;
	        Node* right;
	        bool isLeaf;
	        
	        Node(string symbol, int frequency){
	            this->symbol = symbol;
	            this->frequency = frequency;
	            this->left = NULL;
	            this->right = NULL;
	            this->isLeaf = false;
	        }
	    };
	    
	    struct CompareNode{
	        bool operator()(Node* a, Node* b){
	            return a->frequency > b->frequency;
	        }
	    };
	    
	    void preOrder(Node* node, string path, vector<string>&result){
	        if(node == NULL){
	            return;
	        }
	        
	        if(node->isLeaf){
	            result.push_back(path);
	        }
	        
	        preOrder(node->left, path+"0", result);
	        preOrder(node->right, path+"1", result);
	    }
	
		vector<string> huffmanCodes(string S,vector<int> f,int N)
		{
		    priority_queue<Node*, vector<Node*>, CompareNode> pq;
		    Node *node,*node1,*node2,*newNode,*root;
		    vector<string> result;
		    
		    for(int i=0; i<N; i++){
		        node = new Node(string(1,S[i]),f[i]);
		        node->isLeaf = true;
		        pq.push(node);
		    }
		    
		    while(pq.size() != 1){
		        node1 = pq.top();
		        pq.pop();
		        
		        node2 = pq.top();
		        pq.pop();
		        
		        newNode = new Node((node1->symbol+node2->symbol), (node1->frequency+node2->frequency));
		        newNode->left = node1;
		        newNode->right = node2;
		        pq.push(newNode);
		    }
		    
		    root = pq.top();
		    
		    preOrder(root, "", result);
		    
		    return result;
		}
};
0
putyavka2 months ago
struct Node {
    int f, i;
    Node *l, *r;
    Node(int f, char i=-1, Node*l=NULL, Node*r=NULL)
        : f(f), i(i), l(l), r(r) {
    }
};
struct NodeCmp {
    bool operator()(const Node* a, const Node* b) {
        return a->f > b->f;
    }
};
void deleteNodeR(Node* node) {
    if (!node) return;
    deleteNodeR(node->l);
    deleteNodeR(node->r);
    delete node;
}
void printR(Node* n, string& s, vector<string>& R) {
    if (n->i > -1) R.push_back(s);
    else {
        s.push_back('0');
        printR(n->l, s, R);
        s.pop_back();
        s.push_back('1');
        printR(n->r, s, R);
        s.pop_back();
    }
}
vector<string> huffmanCodes(string S,vector<int> f,int N)
{
    priority_queue<Node*, vector<Node*>, NodeCmp> Q;
    for (int i = 0; i < N; i++)
        Q.push(new Node(f[i], i));
    while (Q.size() > 1) {
        auto l = Q.top(); Q.pop();
        auto r = Q.top(); Q.pop();
        Q.push(new Node(l->f + r->f, -1, l, r));
    }
    vector<string> R;
    string s;
    printR(Q.top(), s, R);
    deleteNodeR(Q.top());
    return R;
}
0
utsavj5023 months ago
#User function Template for python3
from heapq import heapify, heappush, heappop
class Node : 
    def __init__(self,freq,symbol,left=None,right=None) : 
        self.freq=freq
        self.symbol=symbol
        self.left=left
        self.right=right
    def __lt__(self, other):
        return self.freq < other.freq

class Solution:
    def traverse(self,root,ans,curr) : 
        if(root==None) : return;
        if(root.symbol!="$" and root.left==None and root.right==None) : 
            ans.append(curr)
            return;
        self.traverse(root.left,ans,curr+'0')
        self.traverse(root.right,ans,curr+'1')
        
    def huffmanCodes(self,S,f,N):
        heap=[]
        heapify(heap)
        for i in range(N) : 
            heappush(heap,Node(f[i],S[i]))
        while len(heap)>1 : 
            left=heappop(heap)
            right=heappop(heap)
            node=Node(left.freq+right.freq,"$",left,right)
            heappush(heap,node)
        ans=[]
        self.traverse(heappop(heap),ans,"")
        return ans
        # Code here

#{ 
#  Driver Code Starts
#Initial Template for Python 3


if __name__ == '__main__':
	t=int(input())
	for i in range(t):
		S= input()
		N= len(S);
		f= [int(x) for x in input().split()]
		ob = Solution()
		ans = ob.huffmanCodes(S,f,N)
		for i in ans:
		    print(i, end = " ")
		print()
# } Driver Code Ends
+1
revolverocelot3 months ago
For C++. Athough using greater<int> gurantees the constraint mentioned in the ‘note’ of this question. However after running a test case I saw it actually violates it, which results in the testcase getting failed.
So instead of greater<>, while intialising prioirty_queue, define your own comparator block as under
struct comp       {           bool operator()( yourDataType a, yourDataType b)           {               return a→data > b→data;           }       };
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.