Q51 Maximum Frequency Stack - LeetCode
        
                
            
        
        
        
        Mon Jan 30 2023 15:44:41 GMT+0000 (Coordinated Universal Time)
        Saved by
            @Ayush_dabas07
        
        
            
                class FreqStack {
    
    //make 2 HM 1->(frequency , stack) 2->(value , frequency)
        
        //adding same frequency values together in stack
        HashMap<Integer,Stack<Integer>> freq ;
        //which frequency does value belongs to  
        HashMap<Integer,Integer> pos ;
        //also a max frequency to keep track of max frequency
        int max;
    
    //constructor
    public FreqStack() {
        this.freq = new HashMap<>();
        this.pos = new HashMap<>();
        this.max = 0;
    }
    
    public void push(int val) {
            //get position of val or default 
            int position = pos.getOrDefault(val,0);
            position++;
            //update position
            pos.put(val , position);
            //create a stack if its a new frequency
            if(freq.containsKey(position)==false)
            freq.put(position,new Stack<>());
            //push the character
            freq.get(position).push(val);
            
            //update max frequency
            max = Math.max(max,position);
    }
    
    public int pop() {
        int val = freq.get(max).pop();  //removing max frequency element
        
        //updating max and position frequency
        pos.put(val,max-1);
        if(freq.get(max).size()==0) //if max frequency stack becomes empty
        max--;
        return val;
    }
}
/**
 * Your FreqStack object will be instantiated and called as such:
 * FreqStack obj = new FreqStack();
 * obj.push(val);
 * int param_2 = obj.pop();
 */
             
            content_copyCOPY
         
        
        https://leetcode.com/problems/maximum-frequency-stack/
     
  
        
Comments