Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Stack
  • Practice Stack
  • MCQs on Stack
  • Stack Tutorial
  • Stack Operations
  • Stack Implementations
  • Monotonic Stack
  • Infix to Postfix
  • Prefix to Postfix
  • Prefix to Infix
  • Advantages & Disadvantages
Open In App
Next Article:
Check if a given array is pairwise sorted or not
Next article icon

Check if all array elements are present in a given stack or not

Last Updated : 10 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a stack of integers S and an array of integers arr[], the task is to check if all the array elements are present in the stack or not.

Examples:

Input: S = {10, 20, 30, 40, 50}, arr[] = {20, 30}
Output: Yes
Explanation:
Elements 20 and 30 are present in the stack.

Input: S = {50, 60}, arr[] = {60, 50}
Output: Yes
Explanation:
Elements 50 and 60 are present in the stack.

Approach: The idea is to maintain the frequency of array elements in a Hashmap. Now, while the stack is not empty, keep popping the elements out from the stack and reduce the frequency of elements from the Hashmap. Finally, when the stack is empty, check that the frequency of every element in the hash-map is zero or not. If found to be true, print Yes. Otherwise, print No.

Below is the implementation of the above approach:

C++




// C++ program of the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to check if all array
// elements is present in the stack
bool checkArrInStack(stack<int>s, int arr[],
                                  int n)
{
    map<int, int>freq;
     
    // Store the frequency
    // of array elements
    for(int i = 0; i < n; i++)
        freq[arr[i]]++;
         
    // Loop while the elements in the
    // stack is not empty
    while (!s.empty())
    {
        int poppedEle = s.top();
        s.pop();
         
        // Condition to check if the
        // element is present in the stack
        if (freq[poppedEle])
            freq[poppedEle] -= 1;
    }
    if (freq.size() == 0)
        return 0;
         
    return 1;
}
 
// Driver code
int main()
{
    stack<int>s;
    s.push(10);
    s.push(20);
    s.push(30);
    s.push(40);
    s.push(50);
     
    int arr[] = {20, 30};
     
    int n = sizeof arr / sizeof arr[0];
     
    if (checkArrInStack(s, arr, n))
        cout << "YES\n";
    else
        cout << "NO\n";
}
 
// This code is contributed by Stream_Cipher
 
 

Java




// Java program of
// the above approach
import java.util.*;
class GFG{
 
// Function to check if all array
// elements is present in the stack
static boolean checkArrInStack(Stack<Integer>s,
                               int arr[], int n)
{
  HashMap<Integer,
          Integer>freq = new HashMap<Integer,
                                     Integer>();
   
  // Store the frequency
  // of array elements
  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);
 
  // Loop while the elements in the
  // stack is not empty
  while (!s.isEmpty())
  {
    int poppedEle = s.peek();
    s.pop();
 
    // Condition to check if the
    // element is present in the stack
    if (freq.containsKey(poppedEle))
      freq.put(poppedEle, freq.get(poppedEle) - 1);
  }
  if (freq.size() == 0)
    return false;
  return true;
}
 
// Driver code
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("YES\n");
  else
    System.out.print("NO\n");
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python program of
# the above approach
 
# Function to check if all array
# elements is present in the stack
def checkArrInStack(s, arr):
  freq = {}
   
  # Store the frequency
  # of array elements
  for ele in arr:
    freq[ele] = freq.get(ele, 0) + 1
   
  # Loop while the elements in the
  # stack is not empty
  while s:
    poppedEle = s.pop()
     
    # Condition to check if the
    # element is present in the stack
    if poppedEle in freq:
      freq[poppedEle] -= 1
       
      if not freq[poppedEle]:
        del freq[poppedEle]
  if not freq:
    return True
  return False
 
# Driver Code
if __name__ == "__main__":
  s = [10, 20, 30, 40, 50]
  arr = [20, 30]
   
  if checkArrInStack(s, arr):
    print("YES")
  else:
    print("NO")
      
 
 

C#




// C# program of
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to check if all array
// elements is present in the stack
static bool checkArrInStack(Stack<int>s,
                            int []arr, int n)
{
  Dictionary<int,
             int>freq = new Dictionary<int,
                                       int>();
   
  // Store the frequency
  // of array elements
  for(int i = 0; i < n; i++)
    if(freq.ContainsKey(arr[i]))
      freq[arr[i]] = freq[arr[i]] + 1;
  else
    freq.Add(arr[i], 1);
 
  // Loop while the elements in the
  // stack is not empty
  while (s.Count != 0)
  {
    int poppedEle = s.Peek();
    s.Pop();
 
    // Condition to check if the
    // element is present in the stack
    if (freq.ContainsKey(poppedEle))
      freq[poppedEle] = freq[poppedEle] - 1;
  }
  if (freq.Count == 0)
    return false;
  return true;
}
 
// Driver code
public static void Main(String[] args)
{
  Stack<int> s = new Stack<int>();
  s.Push(10);
  s.Push(20);
  s.Push(30);
  s.Push(40);
  s.Push(50);
  int []arr = {20, 30};
  int n = arr.Length;
 
  if (checkArrInStack(s, arr, n))
    Console.Write("YES\n");
  else
    Console.Write("NO\n");
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
 
// JavaScript program of the above approach
 
// Function to check if all array
// elements is present in the stack
function checkArrInStack(s, arr, n)
{
    var freq = new Map();
     
    // Store the frequency
    // of array elements
    for(var i = 0; i < n; i++)
    {
        if(freq.has(arr[i]))
            freq.set(arr[i], freq.get(arr[i])+1)
        else   
            freq.set(arr[i], 1)
    }
         
    // Loop while the elements in the
    // stack is not empty
    while (s.length!=0)
    {
        var poppedEle = s[s.length-1];
        s.pop();
         
        // Condition to check if the
        // element is present in the stack
        if (freq.has(poppedEle))
            freq.set(poppedEle, freq.get(poppedEle)-1);
    }
    if (freq.size == 0)
        return 0;
         
    return 1;
}
 
// Driver code
var s = [];
s.push(10);
s.push(20);
s.push(30);
s.push(40);
s.push(50);
 
var arr = [20, 30];
 
var n = arr.length;
 
if (checkArrInStack(s, arr, n))
    document.write( "YES");
else
    document.write( "NO");
 
 
 
</script>
 
 
Output: 
YES

Time Complexity: O(N)
Auxiliary Space: O(N)



Next Article
Check if a given array is pairwise sorted or not

A

anhiti1999
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Searching
  • Stack
  • frequency-counting
Practice Tags :
  • Arrays
  • Hash
  • Searching
  • Stack

Similar Reads

  • Check if an array contains all elements of a given range
    An array containing positive elements is given. 'A' and 'B' are two numbers defining a range. Write a function to check if the array contains all elements in the given range. Examples : Input : arr[] = {1 4 5 2 7 8 3} A : 2, B : 5Output : YesInput : arr[] = {1 4 5 2 7 8 3} A : 2, B : 6Output : NoRec
    15+ min read
  • Check if a given array is pairwise sorted or not
    An array is considered pairwise sorted if each successive pair of numbers is in sorted (non-decreasing) order. In case of odd elements, last element is ignored and result is based on remaining even number of elements. Examples: Input : arr[] = {10, 15, 9, 9, 1, 5}; Output : Yes Pairs are (10, 15), (
    5 min read
  • Check whether K times of a element is present in array
    Given an array arr[] and an integer K, the task is to check whether K times of any element are also present in the array. Examples : Input: arr[] = {10, 14, 8, 13, 5}, K = 2 Output: Yes Explanation: K times of 5 is also present in an array, i.e. 10. Input: arr[] = {7, 8, 5, 9, 11}, K = 3 Output: No
    8 min read
  • All elements in an array are Same or not?
    Given an array, check whether all elements in an array are the same or not. Examples: Input : "Geeks", "for", "Geeks" Output : Not all Elements are Same Input : 1, 1, 1, 1, 1 Output : All Elements are Same Method 1 (Hashing): We create an empty HashSet, insert all elements into it, then we finally s
    5 min read
  • Find elements which are present in first array and not in second
    Given two arrays, the task is that we find numbers which are present in first array, but not present in the second array. Examples : Input : a[] = {1, 2, 3, 4, 5, 10}; b[] = {2, 3, 1, 0, 5};Output : 4 10 4 and 10 are present in first array, butnot in second array.Input : a[] = {4, 3, 5, 9, 11}; b[]
    14 min read
  • Check for an array element that is co-prime with all others
    Given an array arr[] of positive integers where 2 ? arr[i] ? 106 for all possible values of i. The task is to check whether there exists at least one element in the given array that forms co-prime pair with all other elements of the array. If no such element exists then print No else print Yes. Exam
    14 min read
  • Check if elements of Linked List are present in pair
    Given a singly linked list of integers. The task is to check if each element in the linked list is present in a pair i.e. all elements occur even no. of times. Examples: Input: 1 -> 2 -> 3 -> 3 -> 1 -> 2Output: YesInput: 10 -> 20 -> 30 -> 20Output: No Method : Using MapWe wil
    5 min read
  • Check if Array elements of given range form a permutation
    Given an array arr[] consisting of N distinct integers and an array Q[][2] consisting of M queries of the form [L, R], the task for each query is to check if array elements over the range [L, R] forms a permutation or not. Note: A permutation is a sequence of length N containing each number from 1 t
    13 min read
  • Check if a key is present in every segment of size k in an array
    Given an array arr[] and size of array is n and one another key x, and give you a segment size k. The task is to find that the key x present in every segment of size k in arr[].Examples: Input : arr[] = { 3, 5, 2, 4, 9, 3, 1, 7, 3, 11, 12, 3} x = 3 k = 3 Output : Yes Explanation: There are 4 non-ove
    8 min read
  • Check if the elements of stack are pairwise sorted
    Given a stack of integers, write a function pairWiseSorted() that checks whether numbers in the stack are pairwise sorted or not. The pairs must be increasing, and if the stack has an odd number of elements, the element at the top is left out of a pair. The function should retain the original stack
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences