Thursday, 6 July 2017

Angular $broadcast ,$On and $emit for novice

Intercommunication and eventing :- $brodcast and $emit falls under intercommunication between controllers. There are other ways also like having data in parent and root controller and one other way is getting data from service. $on is unitized for event registering on scopes. Broadcast is like jms broadcasting it will send a copy to everyone. Emit will send it only to its parents  its something like inheritance in java. Please have a look at below program and output to understand it clearly.

Example :- 
<!doctype html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script >
"use strict";
var allScopes = {};
      var angModule = angular.module("app",[]);
function globalController(ctrlName){
  return function($scope){
  console.log("entering controller");
          //Registering event on individual scope
     $scope.$on("customMessage",function(e,opt){
     console.log("Controller :-"+ ctrlName + " recievedMessage "+opt.message);
 })
allScopes[ctrlName]=$scope;
  };  
}
angModule.controller("tcmController",globalController("tcmController"))
.controller("projectController",globalController("projectController"))
.controller("defectsController",globalController("defectsController"))
.controller("jiraController",globalController("jiraController"))
.controller("rtcController",globalController("rtcController"))
.run(function($timeout,$rootScope){
 console.log("entering run");
          //Registering event on global scope
  $rootScope.$on("customMessage",function(e,opt){
     console.log("root Controller recievedMessage "+opt.message);
 });
  allScopes["root"]= $rootScope;  
  $timeout(function(){
   console.log("entering timeout");
//broadcast will communicate to everyone in the scope
     $rootScope.$broadcast("customMessage",{
    message : 'broadcasting from root'
 });

 //emit will communicate to everyone in the inheritance heiracrhy scope
     allScopes["projectController"].$broadcast("customMessage",{
    message : 'broadcasting from root'
 });

 //To see the result run them individually by commenting them out
  },1000);
});
</script>
 
  </head>
  <body>
 <div  ng-app="app">
    <div  ng-controller="tcmController">
       <div  ng-controller="projectController">
       </div>
  <div  ng-controller="defectsController">  
       </div>
   </div>
       <div  ng-controller="jiraController">  
       </div>
  <div  ng-controller="rtcController">  
      </div>
</div>
  </body>
</html>

Output for $emit :- 
Controller :-projectController recievedMessage broadcasting from root
Controller :-tcmController recievedMessage broadcasting from root
 root Controller recievedMessage broadcasting from root


Output for $broadcast:-
root Controller recievedMessage broadcasting from root
Controller :-tcmController recievedMessage broadcasting from root
Controller :-projectController recievedMessage broadcasting from root
Controller :-defectsController recievedMessage broadcasting from root
Controller :-jiraController recievedMessage broadcasting from root
Controller :-rtcController recievedMessage broadcasting from root

Wednesday, 5 July 2017

Angular $watch explanation for novice person

Angular $watch :- To get clear understanding on $watch below i have implemented the example using $watch and without using it. In one liner definitions we can watch on variables based on changes to it we can correspondingly change the variables dependent on it in angular scope. Something like observer pattern but exactly not like that

Example :-  In this example we will have a text box and a label beside to display computed fund based on initial fund release.
<!doctype html>
<html ng-app="app">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script >
         var angModule = angular.module("app",[]);
angModule.controller("checkWatchProperty",function($scope){
      $scope.funding = {startingEstimate:0}
                          //without watch    
 $scope.computeNeeded = function(){        
   $scope.funding.needed = $scope.funding.startingEstimate*10;
  }
   //with watch  
   $scope.$watch('funding.startingEstimate', function(){        
   $scope.funding.needed = $scope.funding.startingEstimate*10;
  });
});
</script>
 
  </head>
  <body ng-controller="checkWatchProperty">
  <!--With out watch -->
   Starting : <input ng-model="funding.startingEstimate" ng-change="computeNeeded()">
    <!--With  watch we no need to attach the ng-change as previous statement. Angular takes care of invoking callback function-->
   Starting : <input ng-model="funding.startingEstimate" >
   Recommendation : {{funding.needed}}
  </body>
</html>

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;
        }    }

}

Tuesday, 31 January 2017

Merge two sorted linked lists

You’re given the pointer to the head nodes of two sorted linked lists. The data in both lists will be sorted in ascending order. Change the next pointers to obtain a single, merged linked list which also has data in ascending order. Either head pointer given may be null meaning that the corresponding list is empty.
Input Format 
You have to complete the Node* MergeLists(Node* headA, Node* headB) method which takes two arguments - the heads of the two sorted linked lists to merge. You should NOT read any input from stdin/console.
Output Format 
Change the next pointer of individual nodes so that nodes from both lists are merged into a single list. Then return the head of this merged list. Do NOT print anything to stdout/console.
Sample Input
1 -> 3 -> 5 -> 6 -> NULL
2 -> 4 -> 7 -> NULL

15 -> NULL
12 -> NULL

NULL 
1 -> 2 -> NULL
Sample Output
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
12 -> 15 -> NULL
1 -> 2 -> NULL
Code :- 
/*
  Merge two linked lists 
  head pointer input could be NULL as well for empty list
  Node is defined as 
  class Node {
     int data;
     Node next;
  }
*/

Node MergeLists(Node headA, Node headB) {
     // This is a "method-only" submission. 
     // You only need to complete this method 
    if(headA==null){
        return headB;
    }else if(headB==null){
        return headA;
    }else{
         Node currentHead = null;
         Node prev = null;
         Node first = headA;
         Node second = headB; 
         while(second!=null && first!=null){                                            
                 if(first.data>second.data){  
                     Node temp = second.next; 
                     second.next = null;
                     if(currentHead!=null || prev!=null){
                         Node inTemp = prev.next ;                       
                         prev.next = second;
                         second.next = inTemp;
                     }else{  
                       second.next = first; 
                       if(prev==null){
                         currentHead =second;
                       }
                       prev = second;
                     }
                      second = temp;
                 }else{
                         prev=first;
                         if(currentHead==null){
                            currentHead = first;
                         }
                        if(first.next==null){
                             first.next=second;
                            break;
                        }  
                         first=first.next;                         
                 }
                
             }
        if(currentHead!=null){
            return currentHead;
        }else{
            return first;
        }
    }
    

}




Saturday, 28 January 2017

Queen's Attack II solving the problem

queen is standing on an  chessboard. The chessboard's rows are numbered from  to , going from bottom to top; its columns are numbered from  to , going from left to right. Each square on the board is denoted by a tuple, , describing the row, , and column, , where the square is located.
The queen is standing at position  and, in a single move, she can attack any square in any of the eight directions (left, right, up, down, or the four diagonals). In the diagram below, the green circles denote all the cells the queen can attack from :
image
There are  obstacles on the chessboard preventing the queen from attacking any square that has an obstacle blocking the the queen's path to it. For example, an obstacle at location  in the diagram above would prevent the queen from attacking cells , and :
image
Given the queen's position and the locations of all the obstacles, find and print the number of squares the queen can attack from her position at .
Input Format
The first line contains two space-separated integers describing the respective values of  (the side length of the board) and  (the number of obstacles).
The next line contains two space-separated integers describing the respective values of  and , denoting the position of the queen.
Each line  of the  subsequent lines contains two space-separated integers describing the respective values of  and , denoting the position of obstacle .
Constraints
  • A single cell may contain more than one obstacle; however, it is guaranteed that there will never be an obstacle at position  where the queen is located.
Subtasks
For  of the maximum score:
For  of the maximum score:
Output Format
Print the number of squares that the queen can attack from position .
Sample Input 0
4 0
4 4
Sample Output 0
9
Explanation 0
The queen is standing at position  on a  chessboard with no obstacles:
image
We then print the number of squares she can attack from that position, which is .
Sample Input 1
5 3
4 3
5 5
4 2
2 3
Sample Output 1
10
Explanation 1
The queen is standing at position  on a  chessboard with  obstacles:
image
We then print the number of squares she can attack from that position, which is .
Code :-
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[][] chessBoard = new int[n][n];
        int rQueen = in.nextInt()-1;
        int cQueen = in.nextInt()-1;
        int sum = 0;
        chessBoard[rQueen][cQueen] = 1;
        for(int a0 = 0; a0 < k; a0++){
            int rObstacle = in.nextInt()-1;
            int cObstacle = in.nextInt()-1;
            // your code goes here
            chessBoard[rObstacle][cObstacle]=-1;
        }
        //check all 8 ways
        // and down
        for(int i =rQueen+1;i<n;i++){
            if(chessBoard[i][cQueen] ==0){
                sum+=1;
            }else{
                break;
            }
        }
         for(int i =rQueen-1;i>=0;i--){
              if(chessBoard[i][cQueen] ==0){
                sum+=1;
            }else{
                break;
            }
        }
        //left and right
         for(int i =cQueen+1;i<n;i++){
              if(chessBoard[rQueen][i] ==0){
                sum+=1;
            }else{
                break;
            }
        }
         for(int i =cQueen-1;i>=0;i--){
              if(chessBoard[rQueen][i] ==0){
                sum+=1;
            }else{
                break;
            }
        }
        //diagonal right
        for(int row =rQueen-1,col=cQueen+1;row>=0 && col<n;row--,col++){
              if(chessBoard[row][col] ==0){
                sum+=1;
            }else{
                break;
            }
        }
         for(int row =rQueen+1,col=cQueen-1;row<n && col>=0;row++,col--){
              if(chessBoard[row][col] ==0){
                sum+=1;
            }else{
                break;
            }
        }
        
         //diagonal left
        for(int row =rQueen-1,col=cQueen-1;row>=0 && col>=0;row--,col--){
              if(chessBoard[row][col] ==0){
                sum+=1;
            }else{
                break;
            }
        }
         for(int row =rQueen+1,col=cQueen+1;row<n && col<n;row++,col++){
              if(chessBoard[row][col] ==0){
                sum+=1;
            }else{
                break;
            }
        }
        
        System.out.println(sum);
    }
}

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