HackerRank Day 18 Solution in Python: Queues and Stacks

Today we will see the HackerRank Day 18 Solution in Python. The problem is named Queues and Stacks, part of 30 Days of code on HackerRank. Let’s get started!

Day 18: Queues and Stacks Problem statement

To solve this challenge, we must first take each character in the input String, enqueue it in a queue, and push that same character onto a stack. Once that’s done, we must dequeue the first character from the queue and pop the top character off the stack, then compare the two characters to see if they are the same; as long as the characters match, we continue dequeueing, popping, and comparing each character until our containers are empty (a non-match means the input String isn’t a palindrome).

Sample Input


Sample Output

The word, madam, is a palindrome.

Explanation: The input string is a palindrome, hence we got the output as The word, the racecar is a palindrome.

You can solve the problem here.

HackerRank Day 18 Solution in Python

import sys

#Create Solution class
class Solution:
    #Constructor for Solution class
    def __init__(self):
        self.mystack = list()
        self.myqueue = list()
    #Method to push character into stack
    def pushCharacter(self, char):
    #Method to push character into queue
    def enqueueCharacter(self, char):

    #Method to pop character from stack
    def popCharacter(self):
    #Method to pop character from queue
    def dequeueCharacter(self):

# read the input string 

#Create the Solution class object

# push/enqueue all the characters of string s to stack
for i in range(l):
pop the top character from stack
dequeue the first character from queue
compare both the characters
for i in range(l // 2):
    if obj.popCharacter()!=obj.dequeueCharacter():
#finally print whether string is palindrome or not.
if isPalindrome:
    print("The word, "+s+", is a palindrome.")
    print("The word, "+s+", is not a palindrome.")    

Code Explanation:

  1. First, inside the Solution class create a constructor and initialize the two instance variables one for Queue and one for Stack.
  2. Then create the pushCharacter method that pushes a character onto a stack.
  3. Then create the enqueueCharacter method that enqueues a character in the queue instance variable.
  4. Then create the popCharacter method that pops and returns the character at the top of the stack instance variable.
  5. Then create the dequeueCharacter() method that dequeues and returns the first character in the queue instance variable.

Also Read:


Author: Ayush Purawr