Showing posts with label Hacker Rank. Show all posts
Showing posts with label Hacker Rank. Show all posts

Hacker Rank - Day 23 : BST Level-Order Traversal

                   Day 23 : BST Level-Order Travarsal

Solution In Java 8:

import java.util.*;

import java.io.*;


class Node{

    Node left,right;

    int data;

    Node(int data){

        this.data=data;

        left=right=null;

    }

}

class Solution{


static void levelOrder(Node root){
      Queue<Node> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            Node curr = queue.remove();
            System.out.print(curr.data + " ");

            if (curr.left != null) queue.add(curr.left);
            if (curr.right != null) queue.add(curr.right);
        }
    }

public static Node insert(Node root,int data){
        if(root==null){
            return new Node(data);
        }
        else{
            Node cur;
            if(data<=root.data){
                cur=insert(root.left,data);
                root.left=cur;
            }
            else{
                cur=insert(root.right,data);
                root.right=cur;
            }
            return root;
        }
    }
    public static void main(String args[]){
            Scanner sc=new Scanner(System.in);
            int T=sc.nextInt();
            Node root=null;
            while(T-->0){
                int data=sc.nextInt();
                root=insert(root,data);
            }
            levelOrder(root);
        }
}


Solution In Python 3: 

import sys

class Node:
    def __init__(self,data):
        self.right=self.left=None
        self.data = data
class Solution:
    def insert(self,root,data):
        if root==None:
            return Node(data)
        else:
            if data<=root.data:
                cur=self.insert(root.left,data)
                root.left=cur
            else:
                cur=self.insert(root.right,data)
                root.right=cur
        return root
    def levelOrder(self, root):
        queue = [root]
        while len(queue) is not 0:
            curr = queue[0]
            queue = queue[1:]
            print(str(curr.data) + " ", end="")

            if curr.left is not None:
                queue.append(curr.left)
            if curr.right is not None:
                queue.append(curr.right)
T=int(input())
myTree=Solution()
root=None
for i in range(T):
    data=int(input())
    root=myTree.insert(root,data)
myTree.levelOrder(root)


Share:

Hacker Rank - Day 22 : Binary Search Trees

                   Day 22 : Binary Search Trees

Solution In Java 8:


import java.util.*;

import java.io.*;

class Node{

    Node left,right;

    int data;

    Node(int data){

        this.data=data;

        left=right=null;

    }

}

class Solution{

public static int getHeight(Node root){
         return root == null ? -1 : 1 + Math.max(getHeight(root.left), getHeight(root.right));
    }
public static Node insert(Node root,int data){
        if(root==null){
            return new Node(data);
        }
        else{
            Node cur;
            if(data<=root.data){
                cur=insert(root.left,data);
                root.left=cur;
            }
            else{
                cur=insert(root.right,data);
                root.right=cur;
            }
            return root;
        }
    }
public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();
        Node root=null;
        while(T-->0){
            int data=sc.nextInt();
            root=insert(root,data);
        }
        int height=getHeight(root);
        System.out.println(height);
    }
}


Solution In Python 3: 

class Node:
    def __init__(self,data):
        self.right=self.left=None
        self.data = data
class Solution:
    def insert(self,root,data):
        if root==None:
            return Node(data)
        else:
            if data<=root.data:
                cur=self.insert(root.left,data)
                root.left=cur
            else:
                cur=self.insert(root.right,data)
                root.right=cur
        return root
    def getHeight(self,root):

        return -1 if root is None else 1 + max(self.getHeight(root.left), self.getHeight(root.right))
T=int(input())
myTree=Solution()
root=None
for i in range(T):
    data=int(input())
    root=myTree.insert(root,data)
height=myTree.getHeight(root)

print(height)       

Share:

Hacker Rank - Day 21 : Generics

                   Day 21 : Generics

Solution In Java 8:


import java.util.*;

class Printer <T> {
    /**
    *    Method Name: printArray
    *    Print each element of the generic array on a new line. Do not return anything.
    *    @param A generic array
    **/
    
   public static <Element> void printArray(Element[] array) {
        for (Element element : array) {
            System.out.println(element);
        }

    }
}

public class Generics {
    
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        Integer[] intArray = new Integer[n];
        for (int i = 0; i < n; i++) {
            intArray[i] = scanner.nextInt();
        }

        n = scanner.nextInt();
        String[] stringArray = new String[n];
        for (int i = 0; i < n; i++) {
            stringArray[i] = scanner.next();
        }
        
        Printer<Integer> intPrinter = new Printer<Integer>();
        Printer<String> stringPrinter = new Printer<String>();
        intPrinter.printArray( intArray  );
        stringPrinter.printArray( stringArray );
        if(Printer.class.getDeclaredMethods().length > 1){
            System.out.println("The Printer class should only have 1 method named printArray.");
        }
    } 

}

Share:

Hacker Rank - Day 20 : Sorting

                                     Day 20 : Sorting

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 temp;
        int n = in.nextInt();
        int a[] = new int[n];
        int numSwaps = 0, firstElement,lastElement;
        
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }
       for (int i = 0; i < n; i++) {
            for (int j = 0; j < n - 1; j++) {
                if (a[j] > a[j + 1]) {
                    temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                    numSwaps++;
                }
            }

            if (numSwaps == 0) {
                break;
            }
       }     
        System.out.println("Array is sorted in "+numSwaps+" swaps.");
        System.out.println("First Element: "+a[0]);
        System.out.println("Last Element: "+a[n-1]);
    }
}

Solution In Python 3: 

#!/bin/python3

import sys


n = int(input().strip())
a = [int(a_temp) for a_temp in input().strip().split(' ')]
numSwaps = 0
for i in range(0,n):
    for j in range(0,n-1):
        if(a[j] > a[j+1]):
            temp = a[j]
            a[j] = a[j+1]
            a[j+1] = temp
            numSwaps = numSwaps+1
            
print("Array is sorted in {} swaps.".format(numSwaps))
print("First Element: {}".format(a[0]))
print("Last Element: {}".format(a[n-1]))
Share:

Hacker Rank - Day 19 : Interfaces

                   Day 19 : Interfaces

Solution In Java 8:


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

interface AdvancedArithmetic{
   int divisorSum(int n);
}

class Calculator implements AdvancedArithmetic
{
    public int divisorSum(int n)
        {
            int sum=0;
             for(int i=1;i<=n/2;i++)
             {
                 if(n%i==0)
                 {
                     sum=sum+i;
                 }
             }
                return (sum+n);
        }
}

class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        scan.close();
       
          AdvancedArithmetic myCalculator = new Calculator();
        int sum = myCalculator.divisorSum(n);
        System.out.println("I implemented: " + myCalculator.getClass().getInterfaces()[0].getName() );
        System.out.println(sum);
    }
}


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: