Posts for: #Java

HackerEarth - Mirror Image

Solution

  • Parse input and build the tree by maintaining an index HashMap.
  • Traverse tree and mirror tree simultaneously to find the mirror node.
/* Solution to HackerEarth: Mirror Image
 * URL: https://www.hackerearth.com/practice/data-structures/trees/binary-and-nary-trees/practice-problems/algorithm/mirror-image-2/
 */
import java.util.*;

class TestClass {
    public static void main(String args[] ) throws Exception {
        //Scanner
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int Q = in.nextInt();
        
        Map<Integer, Node> index = new HashMap<>();
        
        // initialize root node
        Node root = new Node(1);
        
        index.put(1, root);
        
        // build tree
        for(int i=0; i < N-1; i++){
            int parent = in.nextInt();
            int child = in.nextInt();
            char side = in.next().charAt(0);
            
            // get parent node from index
            Node node = index.get(parent);
            
            // create a new child node and add to index
            Node childNode = new Node(child);
            index.put(child, childNode);
            
            if(side == 'L'){
                node.left = childNode;
            }
            else if (side == 'R'){
                node.right = childNode;
            }
        }
        
        // process queries
        for(int i=0; i < Q; i++){
            int target = in.nextInt();
            
            System.out.println(findMirror(root, target));
        }

    }
    
    public static int findMirror(Node root, int target){
        if(root.value == target){
            return target;
        }
        else{
            return recurse(target, root.left, root.right);
        }
    }
    
    public static int recurse(int target, Node left, Node right){

        // no need to further traverse because either current node or mirror node is null
        if(left == null || right == null){
            return -1;
        }
        
        // if target found return mirror node
        if(left.value == target){
            return right.value;
        }
        
        if(right.value == target){
            return left.value;
        }
        
        int mirror = recurse(target, left.left, right.right);
        
        // return mirror if found
        if(mirror > 0){
            return mirror;
        }
        
        return recurse(target, left.right, right.left);
    }
    
    
}

class Node {
    public int value;
    public Node left;
    public Node right;
    
    public Node(int value){
        this.value = value;
    }
}

HackerRank - Largest Permutation

Solution #1

  • Keep indexes of all numbers in a HashMap.
  • Check if current maximum number is already at desired index i.e highest at index 0, second highest at index 1 and so on.
  • If not, keep on swapping them till all the swaps are exhausted.
/* Solution to HackerRank: Largest Permutation
 * URL: https://www.hackerrank.com/challenges/largest-permutation
 */
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 K = in.nextInt();
        
        int[] n = new int[N];
        
        Map<Integer,Integer> index = new HashMap<>();
        
        for(int i = 0; i < N; i++){
            n[i] = in.nextInt();
            
            index.put(n[i],i);
        }
        
        int max = N;
        
        for(int j = 0; j < N ; j++){
            
            int maxIndex = index.get(max);
            
            if(maxIndex != j){
                // make a swap
                K--;
                
                int temp = n[j];
                n[j] = max;
                n[maxIndex] = temp;
                
                // update indexes
                index.put(max,j);
                index.put(temp,maxIndex);
            }
            
            max--;
            
            // break the loop if swaps are exhausted
            if(K == 0){
                break;
            }
        }
        
        for(int i = 0; i < N; i++){
            System.out.print(n[i] + " ");
        }
        
    }
}

Solution #2

  • Find the maximum number in each iteration.
  • Swap them in order of decreasing value till all the swaps are exhausted.

Test cases 13 to 15 timed out for this solution.

HackerRank - Hackerland Radio Transmitters

Solution

  • Iterate through each house in a sorted order.
  • Check if current house is in range of last transmitter.
  • If not, find a house to put transmitter on so that current house is in range.
/* Solution to HackerRank: Hackerland Radio Transmitters
 * URL: https://www.hackerrank.com/challenges/hackerland-radio-transmitters
 */
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 k = in.nextInt();
        int[] x = new int[n];
        for(int x_i=0; x_i < n; x_i++){
            x[x_i] = in.nextInt();
        }
        
        Arrays.sort(x);
        
        int i = 0;
        int range = 0;
        int count = 0;
        
        while(i < n){
            
            if(x[i] < range){
                // current house is already in range of last transmitter
            }
            else{
                count++;

                // check where can the transmitter be placed
                int j = x[i] + k;
                int l = i;

                // transmitter can not be placed farther than j to cover current house,
                // check for the last house within j
                while(l < n && x[l] <= j){
                    l++;
                }
                
                // transmitter is placed at l-1 house
                range = x[--l] + k + 1;
                
                // move counter to l as houses till l are already in range of new transmitter
                i = l;
            }
            
            i++;
        }
        
        System.out.println(count);
    }
}

HackerRank - Minimum Loss

Solution #1

  • Keep prices and corresponding index in a HashMap.
  • Sort the prices array in ascending order so that combination of minimum difference can be found by comparing adjacent prices.
  • Check that the indexes buying and selling are in correct order so that year of buying is less than year of selling.
/* Solution to HackerRank: Minimum Loss
 * URL: https://www.hackerrank.com/challenges/minimum-loss
 */
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();
        long[] p = new long[n];
        
        Map<Long,Integer> index = new HashMap<>();
        
        for(int i=0; i < n; i++){
            p[i] = in.nextLong();
            index.put(p[i], i);
        }
        
        Arrays.sort(p);
        
        long min = Long.MAX_VALUE;
        
        for(int i=0; i < n-1; i++){
            if(p[i+1] - p[i] < min && index.get(p[i+1]) < index.get(p[i])){
                min = p[i+1] - p[i];
            }
        }
        
        System.out.println(min);
    }
}

Solution #2

  • Compare each possible combination to determine the minimum difference.

Test cases 11 to 15 timed out for below solution.

HackerRank Contest - HourRank 24 - Mutual Indivisibility

Solution

  • Start iterating numbers from b to a because combination of larger numbers are more likely to be indivisible.
  • Keep an array representing all numbers including a and b.
  • Strike out multiples of current number from array in each iteration.
/* Solution to HackerRank: Mutual Indivisibility
 * URL: https://www.hackerrank.com/contests/hourrank-24/challenges/mutual-indivisibility
 */
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 t = in.nextInt();
        for(int a0 = 0; a0 < t; a0++){
            int a = in.nextInt();
            int b = in.nextInt();
            int x = in.nextInt();
            
            int[] skills =  new int[b-a+1];
            
            int teamSize = 0;
            
            for(int i=b; i>=a; i--){
                teamSize++;
                    
                int multiple = i*2;
                int count = 2;

                while(multiple <= b){
                    // strike out the multiple, hence decrease team size
                    skills[multiple-a] = 1;
                    teamSize--;

                    count++;
                    multiple = i*count;
                }
                
                // break as needed team size is reached
                if(teamSize == x){
                    break;
                }
            }        
            
            
            if(teamSize >= x){
                int i = skills.length-1;
                
                while(i >= 0 && x > 0){
                   if(skills[i] == 0){
                       System.out.print(i+a);
                       System.out.print(" ");
                       x--;
                   }
                   i--;
                }
                
                System.out.println("");
            }
            else{
                System.out.println(-1);
            }
            
        }
        in.close();
    }
}

HackerRank Contest - Project Euler - Sum Square Difference

Solution

  • Iterate from 1 to given number.
  • Add each iteration to sum and square of it to another sum.
  • Print absolute difference.
/* Solution to HackerRank: Sum Square Difference
 * URL: https://www.hackerrank.com/contests/projecteuler/challenges/euler006
 */
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 t = in.nextInt();
        for(int a0 = 0; a0 < t; a0++){
            int n = in.nextInt();
            
            long squareSum = 0;
            long sum = 0;
            
            for(int i = 1; i <= n; i++){
                squareSum+=(i*i);
                sum+=i;
            }
            
            System.out.println(Math.abs(sum*sum-squareSum));
        }
    }
}

HackerRank Contest - Project Euler - Largest Palindrome

Solution

  • Iterate from the given number to zero.
  • Check if current iteration is a palindrome by using reverse() of StringBuilder class.
  • Check if current iteration is a product of two 3-digit numbers.
/* Solution to HackerRank: Largest Palindrome
 * URL: https://www.hackerrank.com/contests/projecteuler/challenges/euler004
 */
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 t = in.nextInt();
        for(int a0 = 0; a0 < t; a0++){
            int n = in.nextInt();
            
            // decrease n by 1 for first iteration, this will handle test case #3
            while(n-- > 0){
                if(isPalindrome(n) && isProduct(n)){
                    System.out.println(n);
                    break;
                }
            }
        }
    }
    
    static boolean isPalindrome(int n){
        String forward = Integer.toString(n);
        
        return new StringBuilder(forward).reverse().toString().equals(forward);
    }
    
    static boolean isProduct(int n){
        // set boundary value for a 3-digit number
        for(int i = 100; i < 1000; i++){
            // check if the other factor is a 3-digit number
            if(n%i == 0 && n/i > 99 && n/i < 1000){
                return true;
            }
        }
        
        return false;
    }
}

HackerRank Contest - Project Euler - Largest Prime Factor

Solution

  • Find all the factors of the given number by iterating from 1 to square root of the number.
  • Sort all the factors in descending order and iterate to check if a factor is prime.
/* Solution to HackerRank: Largest Prime Factor
 * URL: https://www.hackerrank.com/contests/projecteuler/challenges/euler003
 */
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 t = in.nextInt();
        for(int a0 = 0; a0 < t; a0++){
            long n = in.nextLong();
            
            // get all the factors and sort is descending order
            List<Long> factors = getFactors(n);
            Collections.sort(factors, Collections.reverseOrder());
            
            for(Long factor: factors){
                if(isPrime(factor)){
                    System.out.println(factor);
                    break;
                }
            }
        }
    }
    
    static List<Long> getFactors(long n){
        List<Long> factors = new ArrayList<>();
        
        for(long i = 1; i <= Math.sqrt(n); i++){
            if(n%i == 0){
                factors.add(i);
                factors.add(n/i);
            }
        }
        
        return factors;
    }
    
    static boolean isPrime(long n){
        if(n%2 == 0){
            return false;
        }
        
        for(long i = 3; i <= Math.sqrt(n); i+=2){
            if(n%i == 0){
                return false;
            }
        }
        
        return true;
    }
}