Algorithm


Problem Name: 30 days of code - Day 18: Queues and Stacks

Problem Link: https://www.hackerrank.com/challenges/30-queues-stacks/problem?isFullScreen=true

Welcome to Day 18! Today we're learning about Stacks and Queues. Check out the Tutorial tab for learning materials and an instructional video!

A palindrome is a word, phrase, number, or other sequence of characters which reads the same backwards and forwards. Can you determine if a given string, s , is a palindrome?

To solve this challenge, we must first take each character in s , enqueue it in a queue, and also 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 s isn't a palindrome).

Write the following declarations and implementations:

  1. Two instance variables: one for your stack , and one for your queue.
  2. A void pushCharacter(char ch) method that pushes a character onto a stack.
  3. A void enqueueCharacter(char ch) method that enqueues a character in the queue instance variable.
  4. A char popCharacter() method that pops and returns the character at the top of the stack instance variable.
  5. A char dequeueCharacter() method that dequeues and returns the first character in the queue instance variable.

Input Format

You do not need to read anything from stdin. The locked stub code in your editor reads a single line containing string s. It then calls the methods specified above to pass each character to your instance variables.

Constraints

  • s is composed of lowercase English letters.

Output Format

You are not responsible for printing any output to stdout.
If your code is correctly written and s is a palindrome, the locked stub code will print The word , s, is a palindrome ; otherwise, it will print The word , s, is not a palindrome.

 

Sample Input

racecar

Sample Output

The word, racecar, is a palindrome.

 

 

 

 

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming


#include <iostream>
#include <queue>
#include <stack>

using namespace std;

class Solution {
private:
    queue < char> q;
    stack s;

public:
    char popCharacter() {
        char tmp = s.top();
        s.pop();
        return tmp;
    }

    void pushCharacter(char ch) {
        s.push(ch);
    }

    char dequeueCharacter() {
        char tmp = q.front();
        q.pop();
        return tmp;
    }

    void enqueueCharacter(char ch) {
        q.push(ch);
    }
};

int main() {
    // read the string s.
    string s;
    getline(cin, s);

    // create the Solution class object p.
    Solution obj;

    // push/enqueue all the characters of string s to stack.
    for (int i = 0; i  <  s.length(); i++) {
        obj.pushCharacter(s[i]);
        obj.enqueueCharacter(s[i]);
    }

    bool isPalindrome = true;

    // pop the top character from stack.
    // dequeue the first character from queue.
    // compare both the characters.
    for (int i = 0; i  <  s.length() / 2; i++) {
        if (obj.popCharacter() != obj.dequeueCharacter()) {
            isPalindrome = false;

            break;
        }
    }

    // finally print whether string s is palindrome or not.
    if (isPalindrome) {
        cout << "The word, " << s << ", is a palindrome.";
    } else {
        cout << "The word, " << s << ", is not a palindrome.";
    }

    return 0;
}
Copy The Code & Try With Live Editor

#2 Code Example with C# Programming

Code - C# Programming


using System;
using System.Collections.Generic;
using System.IO;

class Solution
{
    Stack < char> stack;
    Queue queue;

    public Solution()
    {
        stack = new Stack < char>();
        queue = new Queue();
    }

    char popCharacter()
    {
        return stack.Pop();
    }

    void pushCharacter(char c)
    {
        stack.Push(c);
    }

    char dequeueCharacter()
    {
        return queue.Dequeue();
    }

    void enqueueCharacter(char c)
    {
        queue.Enqueue(c);
    }


    static void Main(String[] args) {
        // read the string s.
        string s = Console.ReadLine();
        
        // create the Solution class object p.
        Solution obj = new Solution();
        
        // push/enqueue all the characters of string s to stack.
        foreach (char c in s) {
            obj.pushCharacter(c);
            obj.enqueueCharacter(c);
        }
        
        bool isPalindrome = true;
        
        // pop the top character from stack.
        // dequeue the first character from queue.
        // compare both the characters.
        for (int i = 0; i  <  s.Length / 2; i++) {
            if (obj.popCharacter() != obj.dequeueCharacter()) {
                isPalindrome = false;
                
                break;
            }
        }
        
        // finally print whether string s is palindrome or not.
        if (isPalindrome) {
            Console.Write("The word, {0}, is a palindrome.", s);
        } else {
            Console.Write("The word, {0}, is not a palindrome.", s);
        }
    }
}
Copy The Code & Try With Live Editor

#3 Code Example with Java Programming

Code - Java Programming


import java.util.LinkedList;
import java.util.Scanner;

public class Solution {
    private LinkedList stack;
    private LinkedList queue;

    public Solution() {
        this.stack = new LinkedList();
        this.queue = new LinkedList();
    }

    private char popCharacter() {
        return (char) this.stack.pop();
    }

    private void pushCharacter(char c) {
        this.stack.push(c);
    }

    private char dequeueCharacter() {
        return (char) this.queue.remove(0);
    }

    private void enqueueCharacter(char c) {
        this.queue.addLast(c);
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String input = scan.nextLine();
        scan.close();

        // Convert input String to an array of characters:
        char[] s = input.toCharArray();

        // Create a Solution object:
        Solution p = new Solution();

        // Enqueue/Push all chars to their respective data structures:
        for (char c : s) {
            p.pushCharacter(c);
            p.enqueueCharacter(c);
        }

        // Pop/Dequeue the chars at the head of both data structures and compare them:
        boolean isPalindrome = true;
        for (int i = 0; i  <  s.length / 2; i++) {
            if (p.popCharacter() != p.dequeueCharacter()) {
                isPalindrome = false;
                break;
            }
        }

        //Finally, print whether string s is palindrome or not.
        System.out.println("The word, " + input + ", is "
                + ((!isPalindrome) ? "not a palindrome." : "a palindrome."));
    }
}
Copy The Code & Try With Live Editor

#4 Code Example with Javascript Programming

Code - Javascript Programming


process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});
function readLine() {
    return input_stdin_array[input_currentline++];
}

function Solution() {
  // Current string
  let stack = [];
  // Reversed string
  let queue = [];

  this.pushCharacter = (char) => stack.push(char);
  this.enqueueCharacter = (char) => queue.unshift(char);
  this.popCharacter = () => stack.pop();
  this.dequeueCharacter = () => queue.pop();
}

function main(){
    // read the string s
    var s=readLine();
    var len=s.length;
    // create the Solution class object p
    var obj=new Solution();
    //push/enqueue all the characters of string s to stack
    for(var i = 0;i  <  len; i++){
        obj.pushCharacter(s.charAt(i));
        obj.enqueueCharacter(s.charAt(i));
    }
  
    var isPalindrome=true;
    /*
    pop the top character from stack
    dequeue the first character from queue
    compare both the characters*/

    for(var i = 0; i  <  len/2; i++){
        if(obj.popCharacter()!=obj.dequeueCharacter()){
            isPalindrome=false;
          	break;
        }
    }
    //finally print whether string s is palindrome or not

    if(isPalindrome)
        console.log("The word, "+s+", is a palindrome.");    
    else
        console.log("The word, "+s+", is not a palindrome.");
}
Copy The Code & Try With Live Editor

#5 Code Example with Python Programming

Code - Python Programming


import sys

class Solution:
    def __init__(self):
        self.stack = []
        self.queue = []

    def popCharacter(self):
        return self.stack.pop()

    def pushCharacter(self, char):
        self.stack.append(char)

    def dequeueCharacter(self):
        char = self.queue[0]
        self.queue = self.queue[1:]
        return char

    def enqueueCharacter(self, char):
        self.queue.append(char)

# read the string s
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 s is palindrome or not.
if isPalindrome:
    print("The word, "+s+", is a palindrome.")
else:
    print("The word, "+s+", is not a palindrome.")    
Copy The Code & Try With Live Editor

#6 Code Example with PHP Programming

Code - PHP Programming


stack[] = $stack;
        array_push($this->stack, $stack);
    }

    public function enqueueCharacter($queue)
    {
        $this->queue[] = $queue;
        array_push($this->queue, $queue);
    }

    public function popCharacter()
    {
        return array_pop($this->stack);
    }

    public function dequeueCharacter()
    {
        return array_shift($this->queue);
    }
}

// read the string s
$s = fgets(STDIN);

// create the Solution class object p
$obj = new Solution();

$len = strlen($s);
$isPalindrome = true;

// push/enqueue all the characters of string s to stack
for ($i = 0; $i  <  $len; $i++) {
    $obj->pushCharacter($s{$i});
    $obj->enqueueCharacter($s{$i});
}

/*
pop the top character from stack
dequeue the first character from queue
compare both the characters
*/
for ($i = 0; $i  <  $len / 2; $i++) {
    if($obj->popCharacter() != $obj->dequeueCharacter()){
        $isPalindrome = false;
    	
        break;
    }
}

//finally print whether string s is palindrome or not.
if ($isPalindrome)
    echo "The word, ".$s.", is a palindrome.";
else
    echo "The word, ".$s.", is not a palindrome.";
?>
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Day 17: More Exceptions solution in Hackerrank - Hacerrank solution C, C++, C#, java, Js, Python in 30 days of code
Next
[Solved] Day 19: Interfaces solution in Hackerrank - Hacerrank solution C, C++, C#, java, Js, Python & PHP in 30 days of code