Friday, 26 May 2017

Game of Thrones - I

Dothraki are planning an attack to usurp King Robert's throne. King Robert learns of this conspiracy from Raven and plans to lock the single door through which the enemy can enter his kingdom.
But, to lock the door he needs a key that is an anagram of a certain palindrome string.
The king has a string composed of lowercase English letters. Help him figure out whether any anagram of the string can be a palindrome or not.
Input Format 
A single line which contains the input string.
Constraints 
 length of string  
Each character of the string is a lowercase English letter.
Output Format 
A single line which contains YES or NO in uppercase.
Sample Input : 01
aaabbbb
Sample Output : 01
YES
Explanation 
A palindrome permutation of the given string is bbaaabb
Sample Input : 02
cdefghmnopqrstuvw
Sample Output : 02
NO
Explanation 
You can verify that the given string has no palindrome permutation. 
Sample Input : 03
cdcdcdcdeeeef
Sample Output : 03
YES
CODE:-  main logic is if length is even then count the individual characters in ths string. Each characters duplicate count should be even, Then it ti palendrome. If the string length is odd then there should be only one character whose duplicate count is a odd number.
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 myScan = new Scanner(System.in);
        String inputString = myScan.nextLine(); 
        HashMap<Character,Integer> hashMap = new HashMap<Character,Integer>();
        String ans = "NO";
       for(int i=0;i<inputString.length();i++){
           if(hashMap.containsKey(inputString.charAt(i))){
               hashMap.put(inputString.charAt(i),hashMap.get(inputString.charAt(i))+1);
           }else{
               hashMap.put(inputString.charAt(i),1);
           }
       }
        int oddCount=0;
           Set<Character> set= hashMap.keySet();
           Iterator iter = set.iterator();
           while(iter.hasNext()){
               if(hashMap.get(iter.next())%2!=0){
                   oddCount+=1;
               }
           }
        if(inputString.length()%2==0 && oddCount==0){
                ans = "YES";
        }else if(inputString.length()%2!=0 && oddCount==1){
            ans = "YES";
        }
        System.out.println(ans);
        myScan.close();
    }
}

Thursday, 11 May 2017

Custom hashmap implementation to clear basics of hashmap and hashtable for any software engineer

HashMap/HashTable :- This question arises in most of the interviews. General hashcode and quals contract even fresher will also explain. The main point is why the hash map is faster? why hashmap best time complexity is O(1) without collision?.What is collision what happens when the collision occurs?. what is the internal data structure used in Hash map? and many more questions. Below example will clear all your doubts which has customized hashmap with minimal functionality mimicking actual hashmap/hashtable.

Implementation :- 

package com.shift.tcm.util;

/* Operations performed in custom map */
interface ExtendableMap {
public abstract void put(Object key, Object value);

public abstract Object get(Object key);
}

/* MapEntry is the actual data structure used inside array to store the data*/
class MapEntry<K, V> {
final K key;
V value;
/*
* Incase of duplicates we need to maintain it as a linked list when hash
* code collides
*/
MapEntry<K, V> next;
final int hash;

MapEntry(int h, K k, V v, MapEntry<K, V> n) {
value = v;
next = n;
key = k;
hash = h;
}

public final K getKey() {
return key;
}

public final V getValue() {
return value;
}

// whether two entry objects are equal based on their hashcode and equals
// method
public final boolean equals(Object o) {
if (!(o instanceof MapEntry))
return false;
MapEntry e = (MapEntry) o;
Object k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}

public final int hashCode() {
return key.hashCode();
}

public final String toString() {
return getKey() + "=" + getValue();
}
}

Map impelmentation starts here :- 
public class CustomHashMap implements ExtendableMap {
// Using array will provide random access which returns value in constant
// time
Object[] table;
int length;

// Setting up default size 16
public CustomHashMap() {
this.table = new Object[16];
this.length = 16;
}

// User setting custom size
public CustomHashMap(int size) {
this.table = new Object[size];
this.length = size;
}

@Override
public void put(Object key, Object value) {
int hashKey = calculateHash(key.hashCode());
if (hashKey > -1 && hashKey < length) {
MapEntry entry = new MapEntry(key.hashCode(), key, value, null);
if (table[hashKey] == null) {
table[hashKey] = entry;
} else {
// If there are duplicates we need to form an linkedlist of type
// MapEntry
handleDuplicatesOrUpdateExisting(entry, hashKey);
}
}
}

@Override
public Object get(Object key) {
// Determine hashvalue
int hashKey = calculateHash(key.hashCode());
// Now lookup is very fast because array is an index based hash no need
// to loop through the array
if (hashKey > -1 && hashKey < length) {
MapEntry entry = (MapEntry) table[hashKey];
if (entry.next != null) {
return exactMatchInList(entry, key);
}
return entry.getValue();
}
return null;
}

/*
* If hashcodes are matching then we have to loop through linked list and
* find the exact value

*/
private Object exactMatchInList(MapEntry entry, Object key) {
while (entry!= null) {
if (entry.hashCode() == key.hashCode() && entry.getKey().equals(key)) {
return entry;
} else {
entry = entry.next;
}
}
return null;
}

/*
* If hashcodes are matching then we have to form a linked list and store
* the value

*/
private void handleDuplicatesOrUpdateExisting(MapEntry entry, int hashKey) {
MapEntry prevEntry = (MapEntry) table[hashKey];
if (prevEntry.equals(entry)) {
table[hashKey] = entry;
} else {
prevEntry.next = entry;
table[hashKey] = prevEntry;
}
}

/*
* Base hash function responsible for converting hash key to actual hash
* value Generally many people gets confuse between hashkey and actual hash
* value which is computed to make hashmap respond in constant time to make it work
         * in constant time always
*/
private int calculateHash(int key) {
return key % length;
}

}

End usage of the custom hashmap :-

package com.shift.tcm.util;

/*
 * Test case for unit testing customhashmap
 * 
 * */
public class HashMapTest {

public static void main(String[] args) {
// Initialize the custom hashmap with default size 16
CustomHashMap customHashMap = new CustomHashMap();

//Put data to map
Employee employee= new Employee(2,"krishna");
customHashMap.put(employee, "Manager");
Employee employee1= new Employee(1,"satish");
customHashMap.put(employee1, "Assistent Manager");
                Employee employee4= new Employee(4,"employee");
customHashMap.put(employee4, "Engineer");

//Putting duplicate key data
Employee employee2= new Employee(2,"krishna1");
customHashMap.put(employee2, "Director");
Employee employee3= new Employee(1,"satish1");
customHashMap.put(employee3, "Sr Director");

//Retrieve Data from map;
Employee retrieveEmployee1= new Employee(1,"satish1");
        System.out.println(customHashMap.get(retrieveEmployee1));
Employee retrieveEmployee2= new Employee(2,"krishna");
System.out.println(customHashMap.get(retrieveEmployee2));
                Employee employee5= new Employee(4,"employee");
System.out.println(customHashMap.get(employee5));
}

}

class Employee {
int id;
String name;

public Employee(int id,String name) {
this.id = id;
this.name=name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

/* If hashcode is equals it is not necessary that both the objects are same. 
* In case of duplicate values in hashmap its equals methods is verified to check whether the objects are same are not
*/
@Override
public int hashCode() {
return id;
}

/* If both the objects equals method returns same then its hashcode method should also return same value */
@Override
public boolean equals(Object o) {
if(o instanceof Employee){
Employee employee = (Employee)o;
if(employee.getName()== getName()){
return true;
}else {
return false;
}
}else{
return false;
}
}

public String toString(){
return "Employee ID :- "+id;

}
}

Sunday, 30 April 2017

Sorting array list based on name using collections.sort

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TestClass2 {

public static void main(String[] args) {
// TODO Auto-generated method stub
        ArrayList<Person> list = new ArrayList<Person>();
        list.add(new Person("B"));
        list.add(new Person("A"));
        list.add(new Person("D"));
        list.add(new Person("C"));
        Collections.sort(list,new Comparator<Person>(){
@Override
public int compare(Person arg0, Person arg1) {
return arg0.name.compareToIgnoreCase(arg1.name);
}
       
        });
        for(Person person:list){
        System.out.println(person.name);
        }
}

}

class Person {
String name;
Person(String name){
this.name=name;
}
}

Parsing hash tags twitter trends

Twitter Trends
Twitter shows trends in order to make its users aware of the trending news. These trends are nothing but trending hashtags that the users are tweeting about. For example: If thousands of users are talking about United States by adding a hashtag #US in their tweet, then US will be a trending hashtag. Couple of example tweets with hashtag #US could be:

Donald Trump becomes the 45th #US President
Roger Federer wins #US Open for 5th time
Given a list of
N
N tweets, your task is to find top the five trending hashtags. Each tweet, let's call it
S
S, will contain at least one one word with hashtag. There will be maximum of three hashtags in any tweet. All hashtags in a single tweet will be unique.

Input:
First line of the input will contain   N
N denoting the number of tweets.
Next
N
N lines, each will contain a string S
S.

Output:
Print the top five trending hashtags. In case of tie between any two hashtags, print them in lexicographical order in a new line.

Note:

Any tweet is composed of lowercase and uppercase English letters, digits and spaces.
Any hashtag begins with # and the subsequent characters will only contain lowercase and uppercase English letters and digits.



Sample Input
10
Donald Trump becomes the 45th #US President
Potentially habitable exoplanet #ProximaB discovered
#RogerFederer wins #US Open for 5th time
#GravitationalWaves detection successful
Traces of liquid water discovered on #Mars
Life Could Survive on Exoplanet #ProximaB
Go go #RogerFederer
Ten ways #ProximaB is different from Earth
ISRO becomes 4th space agency to reach #Mars
#RogerFederer beats #Nadal



Sample Output
#ProximaB
#RogerFederer
#Mars
#US
#GravitationalWaves
Explanation
In the given sample test case, the count of occurrences of all the hashtags are:

#US: 2
#Mars: 2
#RogerFederer: 3
#ProximaB: 3
#Nadal: 1
#GravitationalWaves: 1

Sort them by count and in case of tie in count we sort them in lexicographical order of hashtag. It means that Since #RogerFederer and #ProximaB has equal count, we compare the strings and since #ProximaB is lexicographically smaller than #RogerFederer, #ProximaB will have precedence over #RogerFederer.

Final sorted order is:

#ProximaB: 3
#RogerFederer: 3
#Mars: 2
#US: 2
#GravitationalWaves: 1
#Nadal: 1

Top 5 hashtags from the above list is the correct output.


Code :- 

package com.deutsche.Domain;


//imports for BufferedReader
import java.io.BufferedReader;
import java.io.InputStreamReader;

//import for Scanner and other utility classes
import java.util.*;
import java.util.Map.Entry;

class TestClass {
  public static void main(String args[] ) throws Exception {
      //BufferedReader
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      HashMap<String,Integer> hashMap = new HashMap<String,Integer>();
      String line = br.readLine();
      for(int i=0;i<Integer.parseInt(line);i++){
          String line1= br.readLine();
          while(true){
          int index = line1.indexOf('#');
          if(index<0){
              break;
          }
          line1=line1.substring(index,line1.length());
          int spaceIndex = line1.indexOf(' ');
          if(spaceIndex<0){
         spaceIndex=line1.length();
          }
          String tag = line1.substring(0,spaceIndex);
          if(hashMap.containsKey(tag)){
               hashMap.put(tag,hashMap.get(tag)+1);
          }else{
         hashMap.put(tag,1);
          }
          if(spaceIndex==line1.length()){
         break;
          }
          line1 = line1.substring(spaceIndex+1,line1.length());
          }
      }
      Set<Entry<String, Integer>> set = hashMap.entrySet();
      List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
      Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
      {
          public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
          {
         if(o2.getValue() == o1.getValue()){
         return (o1.getKey()).compareToIgnoreCase (o2.getKey());
         }else{
                return (o2.getValue()).compareTo( o1.getValue());
         }
          }
      } );
      int count =0;
       for(Map.Entry<String, Integer> entry:list){
           if(count>5){
               break;
           }
          System.out.println(entry.getKey()+": "+entry.getValue());
          count=count+1;
      }
     
  }
}


Thursday, 6 April 2017

Find factorial for number which are larger than 64 bit in java

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);
        BigInteger big = new BigInteger(String.valueOf(in.nextInt()));
        System.out.println(factorial(big));
    }
   
    static BigInteger factorial(BigInteger n){
        if(n == BigInteger.ONE || n== BigInteger.ZERO)
            return BigInteger.ONE;
        else
            return n.multiply(factorial(n.subtract(BigInteger.ONE)));
    }
}

Tuesday, 14 March 2017

Arraylist contains search for non primitive and custom objects

Searching custom objects in arraylist :- Typical developer quickly codes foreach to check whether the object is matching. Instead of that if your search is always based on constant factor like name or phone number you can override the hashcode and equals method as given below.


public class MainThread {
    private static Object ob1 = new Object();

    public static void main(String[] args) {
        Employee e1 = new Employee("krishna1", 1);
        Employee e2 = new Employee("krishna2", 12);
        Employee e3 = new Employee("krishna3", 13);
        Employee e4 = new Employee("krishna4", 14);
        Employee e5 = new Employee("krishna5", 15);
        Employee e6 = new Employee("krishna6", 16);
        Employee e7 = new Employee("krishna7", 17);
        Employee e8 = new Employee("krishna8", 18);
        Employee e9 = new Employee("krishna9", 19);
        Employee e10 = new Employee("krishna10", 20);
        Employee e11 = new Employee("krishna11", 21);
        Employee e12 = new Employee("krishna12", 22);
        ArrayList<Employee> arrayLis = new ArrayList<Employee>();
        arrayLis.add(e1);
        arrayLis.add(e2);
        arrayLis.add(e3);
        arrayLis.add(e4);
        arrayLis.add(e5);
        arrayLis.add(e6);
        arrayLis.add(e7);
        arrayLis.add(e8);
        arrayLis.add(e9);
        arrayLis.add(e10);
        arrayLis.add(e11);
        arrayLis.add(e12);
        System.out.println(arrayLis.contains(new Employee("krishna2", 12)));

    }
}

class Employee {
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(int phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    int phoneNumber;

    Employee(String name, int phoneNumber) {
        this.name = name;
        this.phoneNumber = phoneNumber;
    }

    //Logic to determine when will the objects will be same
    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Employee) {
            Employee employee = (Employee) obj;
            if (this.name.equals(employee.getName())) {
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }
    }

 //Logic to determine when will the objects will be same
    @Override
    public int hashCode(){
        return this.name.hashCode();
    }

}

Wednesday, 22 February 2017

Merge sort using Java without class level variables

Mergesort :- Only reason to choose this sort is its time complexity is o(nlogn) based on asymptotic analysis.

public class TestClass {

    public static void main(String[] args) {
        // Initialize the array
        int a[] = { 1, 4, 9, 6 };
        mergesort(a, 0, a.length - 1);
        //Finally print the array
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }

    private static void mergesort(int[] a, int low, int high) {
        // check if low is smaller then high, if not then the array is sorted
        if (low < high) {
            int middle = low + (high - low) / 2;
            //Recursive call to left and right
            mergesort(a, low, middle);
            mergesort(a, middle + 1, high);
            // Combine them both
            merge(a, low, middle, high);
        }
    }

    private static void merge(int[] a, int low, int middle, int high) {
       //Create temporary error
        int[] temp = new int[a.length];
        for (int i = low; i <= high; i++) {
            temp[i] = a[i];
        }

        //Initialize variables for looping condition
        int i = low;
        int j = middle + 1;
        int k = low;

        //Loop through first and second array and place smallest in main array
        while (i <= middle && j <= high) {
            if (temp[i] < temp[j]) {
                a[k] = temp[i];
                i = i + 1;
            } else {
                a[k] = temp[j];
                j = j + 1;
            }
            k = k + 1;
        }

       //Loop through left over elements
         // Loop through left over elements
        while (i <= middle) {
            a[k] = temp[i];
            i = i + 1;
            k = k + 1;
        }
        while (j <= high) {
            a[k] = temp[j];
            j = j + 1;
            k = k + 1;
        }    }

}

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...