Showing posts with label HackerRank. Show all posts
Showing posts with label HackerRank. Show all posts

Hacker Rank - Day 18 : Queues and Stacks

                   Day 18 : Queues and Stacks

Solution In Java 8:


import java.io.*;
import java.util.*;

public class Solution {
    Queue <Character> queue = new LinkedList<>();
    Deque <Character> stack = new ArrayDeque<>();
   
    public void pushCharacter(char ch){
        stack.push(ch);
    }
    public void enqueueCharacter(char ch){
        queue.add(ch);
    }
    public char popCharacter(){
        return stack.pop();
    }
    public char dequeueCharacter(){
        return queue.remove();
    }

    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." ) );
    }
}




Solution In Python 3: 

import sys
class Solution:
    def __init__(self):
        self.stack = []
        self.queue = []
    def pushCharacter(self , ch):
        self.stack.append(ch)
    def enqueueCharacter(self , ch):
        self.queue.append(ch)
    def popCharacter(self):
        return self.stack.pop()
    def dequeueCharacter(self):
        ch = self.queue[0]
        self.queue = self.queue[1:]
        return ch       
        

s=input()

obj=Solution()   

l=len(s)

for i in range(l):
    obj.pushCharacter(s[i])
    obj.enqueueCharacter(s[i])
    
isPalindrome=True

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.")    

Share:

Hacker Rank - Day 17 : More Exceptions

                   Day 17 : More Exceptions

Solution In Java 8:


import java.util.*;
import java.io.*;

class Calculator{
    int power(int n , int p) throws Exception
    {
            if(n < 0 || p < 0)
            {
                    throw new Exception("n and p should be non-negative");
            }
        return (int)Math.pow(n,p);
    }
}

class Solution{

    public static void main(String []argh)
    {
        Scanner in = new Scanner(System.in);
        int T=in.nextInt();
        while(T-->0)
        {
            int n = in.nextInt();
            int p = in.nextInt();
            Calculator myCalculator = new Calculator();
            try
            {
                int ans=myCalculator.power(n,p);
                System.out.println(ans);
               
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
            }
        }

    }
}
 


Solution In Python 3: 
class Calculator(Exception):
    def power(self,n,p):
        self.n = n
        self.p = p
        if self.n < 0 or self.p < 0:
            raise Exception("n and p should be non-negative")

        return self.n**self.p
myCalculator=Calculator()
T=int(input())
for i in range(T):
    n,p = map(int, input().split())
    try:
        ans=myCalculator.power(n,p)
        print(ans)
    except Exception as e:
        print(e)  
Share:

Hacker Rank - Day 16 : Exceptions

                       Day 16 : Exceptions

Solution In Java 8:


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String S = in.next();
      
        try{
            Integer i = Integer.parseInt(S);
            System.out.println(i);
          
        }catch(NumberFormatException nfe){
            System.out.println("Bad String");
        }
    }
}

Solution In Python 3: 

#!/bin/python3

import sys

try:
    print(int(input()))
except ValueError:
    print("Bad String")
Share:

Hacker Rank - Day 15 : Linked List

                       Day 15 : Linked List

Solution In Java 8:


import java.io.*;
import java.util.*;

class Node {
    int data;
    Node next;
    Node(int d) {
        data = d;
        next = null;
    }
}

class Solution {

public static  Node insert(Node head,int data) {
        if(head == null){
            head = new Node(data);
        }
        else{
            Node curr = head;
            while(curr.next!=null){
                curr = curr.next ;
            }
            curr.next = new Node(data);
        }
        return head;
    }
public static void display(Node head) {
        Node start = head;
        while(start != null) {
            System.out.print(start.data + " ");
            start = start.next;
        }
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        Node head = null;
        int N = sc.nextInt();

        while(N-- > 0) {
            int ele = sc.nextInt();
            head = insert(head,ele);
        }
        display(head);
        sc.close();
    }
}


Solution In Python 3: 



class Node:
    def __init__(self,data):
        self.data = data
        self.next = None
class Solution:
    def display(self,head):
        current = head
        while current:
            print(current.data,end=' ')
            current = current.next

    def insert(self,head,data):
        if(head == None):
            head = Node(data)
        else:
            curr = head
       
            while curr.next:
                curr = curr.next
            curr.next = Node(data)
        return head    
 
  mylist= Solution()
T=int(input())
head=None
for i in range(T):
    data=int(input())
    head=mylist.insert(head,data)   
mylist.display(head);
     
Share:

Hacker Rank - Day 11 : 2D Arrays

                        Day 11 : 2D Arrays

Solution In Java 8:


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a[][] = new int[6][6];
        int sum = 0;
        for(int i=0; i < 6; i++){
            for(int j=0; j < 6; j++){
                a[i][j] = in.nextInt();
            }
        }
        int max = -99999;
        
        for(int i = 0 ; i < 4 ; i++){
            for(int j= 0 ; j < 4 ; j++){
                sum = a[i][j] + a[i][j+1] + a[i][j+2] + a[i+1][j+1] + a[i+2][j] + a[i+2][j+1] + a[i+2][j+2];
                if(sum > 0) 
                {
                    if(sum > max){
                        max =sum;
                    }
                }
                else{
                    if(max < sum ){
                        max = sum;
                    }
                }
            }
            
            
        }
       
      System.out.println(max);  
    }
}

Solution In Python 3: 

import sys


arr = []
maxi = -9999
for arr_i in xrange(6):
   arr_temp = map(int,raw_input().strip().split(' '))
   arr.append(arr_temp)

for i in range(4):
    for j in range(4):
        addition = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]
        if(addition > 0):
            if(addition > maxi):
                maxi = addition 
        else:
            if(maxi < addition):
                maxi = addition
print(maxi)            
Share:

Hacker Rank - Day 10 : Binary Numbers

                        Day 10 :Binary Numbers

Solution In Java 8:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Long n_to_b = Long.parseLong(Integer.toBinaryString(n));
        int  max = 0, cnt = 0;
        Long n_to_b1 = n_to_b ;
        while(n_to_b1>0)
            {
            Long rem = n_to_b1 % 10;
            if(rem == 1)
                {
                cnt++;
            }
            else{
                cnt = 0;
            }
            if(cnt > max)
                {
                max = cnt;
            }
            n_to_b1 = n_to_b1 / 10;
        }
      
        System.out.print(max);
    }
}
Solution In Python 3: 


#!/bin/python3
no = int(input())
n_to_b = "{0:b}".format(no)
N_TO_B = str(n_to_b)
cnt = 0
maxi = 0
n = N_TO_B
for i in n:
    if(i == '1'):
        cnt=cnt+1
    else:
        cnt = 0
    if(cnt > maxi):
        maxi = cnt
print(maxi)      
Share:

Hacker Rank - Day 9 : Recursion

                        Day 9 :Recursion

Solution In Java 8:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int ans;
        int n = sc.nextInt();
        ans = factorial(n);
        System.out.println(ans);
    }
       public static int factorial(int n){
            if(n == 1){
                return 1;
            }
            else{
                return (n * factorial(n-1));
            }
        }
    }



Solution In Python 3: 



n = int(input().strip())

def factorial(n):
    if n is 1:
        return 1
    else:
        return (n) * factorial(n-1)

ans = factorial(n)
print(ans)
Share:

Hacker Rank - Day 8 : Dictionaries and Maps

                        Day 8 :Dictionaries and Maps

Solution In Java 8:

import java.util.*;
import java.io.*;

class Solution{
    public static void main(String []argh){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        HashMap <String,Integer> hm = new HashMap<String,Integer>();
        for(int i = 0; i < n; i++){
            String name = in.next();
            int phone = in.nextInt();
            hm.put(name,phone);
          
        }
        while(in.hasNext()){
            String s = in.next();
            if(hm.containsKey(s))
                {
                System.out.println(s+"="+hm.get(s));
            }
            else{
                System.out.println("Not found");
            }
        }
        in.close();
    }
}

Solution In Python 3: 

n = int(input().strip())
D = {}
for x in range(n):
    l = input()
    k,v = l.split()
    D[k] = v
  
for x in range(len(D)):
    l = input()
    if l in D.keys():
        print("{}={}".format(l ,D[l]))
    else:
        print("Not found")
Share:

Hacker Rank - Day 7 : Arrays

                        Day 4 :Class vs. Instance

Solution In Java 8:

import java.io.*;
import java.util.*;


public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] arr = new int[n];
        for(int i=0; i < n; i++){
            arr[i] = in.nextInt();
        }
        for(int j = n-1;j >= 0;j--)
            {
            System.out.print(arr[j]+" "); 
        }
  
        in.close();
    }
}

Solution In Python 3: 


import sys

n = int(input().strip())
arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]
for i in range(n-1, -1, -1):
    print(arr[i],end=" ")
   
   
Share:

Hacker Rank - Day 6 : Let's Review

                        Day 6 :Lets Review

Solution In Java 8:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int T = scan.nextInt();
        scan.nextLine();
        for(int i = 0;i < T ;i++ )
            {
            String s = scan.nextLine();
            for(int j = 0;j < s.length() ; j+=2)
                {
                System.out.print(s.charAt(j));
            }
            System.out.print(" ");
            for(int j = 1;j < s.length() ; j+=2)
                {
                System.out.print(s.charAt(j));
            }
            System.out.println();
        }
    }
}

Solution In Python 3: 

n = int (input())
s1 = input()
s2 = input()

for i in range(0,len(s1),2):
    print(s1[i],end="")

print(" ",end = "")
for i in range(1,len(s1),2):
    print(s1[i],end="")
  
print("")
for i in range(0,len(s2),2):
    print(s2[i],end="")

print(" ",end = "")
for i in range(1,len(s2),2):
    print(s2[i],end="")
  
print("")
Share:

Hacker Rank - Day 5 : Loops

                        Day 5 : Loops

Solution In Java 8:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int i = 1;
        while(i<=10)
            {
             
            System.out.println(n+" x "+i+" = "+n*i);
            i++;
        }
    }
}

Solution In Python 3: 
#!/bin/python3

import sys


n = int(input().strip())
if n>=2 and n<=20:
    for i in range(1,11):
        print("%d x %d = %d"%(n ,i,(n*i)))
Share:

Hacker Rank - Day 4 : Class vs. Instance

                        Day 4 :Class vs. Instance

Solution In Java 8:

import java.io.*;
import java.util.*;
public class Person {
    private int age; 

    public Person(int initialAge) {
          this.age = initialAge;
        if(age<0)
        {
            age = 0;
            System.out.println("Age is not valid, setting age to 0.");
        }
    }

    public void amIOld() {
        String str = "";
        if(age < 13)
        {
            str = "You are young."; 
        }
        else if(age >= 13 && age < 18)
        {
            str = "You are a teenager."; 
        }
        else
        {
            str = "You are old."; 
        }
        System.out.println(str);
    }

    public void yearPasses() {
          age ++;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        for (int i = 0; i < T; i++) {
            int age = sc.nextInt();
            Person p = new Person(age);
            p.amIOld();
            for (int j = 0; j < 3; j++) {
                p.yearPasses();
            }
            p.amIOld();
            System.out.println();
        }
        sc.close();
    }
}

Solution In Python 3: 

class Person:
    def __init__(self, initialAge):
        if initialAge > 0:
            self.age = initialAge
        else:
            print("Age is not valid, setting age to 0.")
            self.age = 0
    def amIOld(self):
        if self.age < 13:
            print("You are young.")
        elif self.age < 18:
            print("You are a teenager.")
        else:
        print("You are old.")
    def yearPasses(self):
            self.age += 1

t = int(input())
for i in range(0, t):
    age = int(input())        
    p = Person(age) 
    p.amIOld()
    for j in range(0, 3):
        p.yearPasses()      
    p.amIOld()
    print("")           
Share:

Hacker Rank - Day 3 : Intro to Conditional Statements

                        Day 3 :Intro to Conditional Statements.

Solution In Java 8:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
 
   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      int n = scan.nextInt();
      scan.close();
      String ans="";
        
      if(n%2==1){
         ans = "Weird";
      }
      else if (n>=2 && n<=5){
             ans = "Not Weird";
      }
      else if (n>=6 && n<=20){
          ans = "Weird";
      }
       else{
           ans = "Not Weird";
       }
      System.out.println(ans);
   }
}

Solution In Python 3: 

import sys
N = int(input().strip())
if N%2!=0:
    print("Weird")
elif N>=2 and N<=5:
    print("Not Weird")
elif N>=6 and N<=20:
    print("Weird")
else:
    print("Not Weird")
Share:

Hacker Rank - Day 2 : Operators

                        Day 2 :Operators.

Solution In Java 8:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Arithmetic {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        double mealCost = scan.nextDouble();
        int tipPercent = scan.nextInt();
        int taxPercent = scan.nextInt();
        scan.close();
        double tip = mealCost*((double)tipPercent/100);
        double tax = mealCost*((double)taxPercent/100);
        Double cost = (Double) mealCost + tip + tax ;
        int totalCost = (int) Math.round(cost);
        System.out.println("The total meal cost is "+totalCost+ " dollars.");
    
    
    }
}

Solution In Python 3:

mealCost = float(input())
tipPercent = float(input())
taxPercent = float(input())

Cost = mealCost + (tipPercent/100)*mealCost + (taxPercent/100)*mealCost
round(Cost)
print("The total meal cost is %d dollers."%Cost)


The Solution is Corrent But the Compiler at Hacker Rank Shows Wrong Answer '

Wll be back at this SOON :)

Share:

Hacker Rank - Day 1 : Data Types

                        Day 1 :Data Types.

Solution In Java 8:

import java.io.*;
import java.util.*;

public class Solution
{
    public static void main(String[] args)
    {
        int i = 4;
        double d = 4.0;
        String s = "HackerRank ";

        Scanner scan = new Scanner(System.in);
       
        int i2 = scan.nextInt();
        double d2 = scan.nextDouble();
        scan.nextLine();
        String s2 = scan.nextLine();

        System.out.println(i+i2);
        System.out.println(d+d2);
        System.out.println(s+s2);
       
        scan.close();
    
    }
}

Solution In Python 3:


no = int(input())
dno = float(input())
stri = (input())

print(i + no)
print(d + dno)
print(s + stri)

Share:

Hacker Rank - Day 0 : Hello World.

                        Day 0 :Hello World.

Solution In Java 8: 

import java.io.*;
import java.util.*;

public class Solution 

{
    public static void main(String[] args) 

    {

        Scanner scan = new Scanner(System.in);
        String inputString = scan.nextLine();
        System.out.println("Hello, World.");
        System.out.println(inputString);
     
    }
}

 

Solution In Python 3:


input_string = input()
print('Hello, World.')

Share: