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

madam

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()
        return(None)
    
    #Method to push character into stack
    def pushCharacter(self, char):
        self.mystack.append(char)
    
    #Method to push character into queue
    def enqueueCharacter(self, char):
        self.myqueue.append(char)

    #Method to pop character from stack
    def popCharacter(self):
        return(self.mystack.pop(-1))
    
    #Method to pop character from queue
    def dequeueCharacter(self):
        return(self.myqueue.pop(0))      

# read the input string 
s=input()

#Create the Solution class object
obj=Solution()   

l=len(s)
# push/enqueue all the characters of string s to stack
for i in range(l):
    obj.pushCharacter(s[i])
    obj.enqueueCharacter(s[i])
    
isPalindrome=True
'''
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():
        isPalindrome=False
        break
    
#finally print whether string is palindrome or not.
if isPalindrome:
    print("The word, "+s+", is a palindrome.")
else:
    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:

Share:

Author: Keerthana Buvaneshwaran