Check if all array elements are present in a given stack or not | Java program of the above approach ; Function to check if all array elements is present in the stack ; Store the frequency of array elements ; Loop while the elements in the stack is not empty ; Condition to check if the element is present in the stack ; Driver code
import java . util . * ; class GFG { static boolean checkArrInStack ( Stack < Integer > s , int arr [ ] , int n ) { HashMap < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( freq . containsKey ( arr [ i ] ) ) freq . put ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) ; else freq . put ( arr [ i ] , 1 ) ; while ( ! s . isEmpty ( ) ) { int poppedEle = s . peek ( ) ; s . pop ( ) ; if ( freq . containsKey ( poppedEle ) ) freq . put ( poppedEle , freq . get ( poppedEle ) - 1 ) ; } if ( freq . size ( ) == 0 ) return false ; return true ; } public static void main ( String [ ] args ) { Stack < Integer > s = new Stack < Integer > ( ) ; s . add ( 10 ) ; s . add ( 20 ) ; s . add ( 30 ) ; s . add ( 40 ) ; s . add ( 50 ) ; int arr [ ] = { 20 , 30 } ; int n = arr . length ; if ( checkArrInStack ( s , arr , n ) ) System . out . print ( "YESNEW_LINE"); else System . out . print ( "NONEW_LINE"); } }