Thursday, 24 August 2017

Left rotation of an array by K steps in JAVA

This is another popular java coding interview question. You can find this question almost every online coding sites like HackerRank, leetcode etc.

We have an array mainArr[]={1,2,3,4,5,6}  and K is given as 3.

So after left rotation, actual array would be mainArr[]={4,5,6,1,2,3}.

Logic: I am using two arrays here. Temp[] array will hold the elements from 0th index to kth index , after that I will merge temp[] and mainArr[] into finalArr[].

Sample code:

/**
 * 
 * @author Sourin
 *
 */
public class LeftRotationOfAnArray {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
System.out.println("Enter the arrays length: \n");
int n=in.nextInt();
System.out.println("Enter the no of rotation needed.. \n");
int k=in.nextInt();
int mainArr[]=new int[n];
for(int i=0; i<n;i++)
{
mainArr[i]=in.nextInt();
}
int finalArr[]=makeLeftRotation(mainArr,n,k);
for(int m:finalArr)
{
System.out.println("After rotations: "+ m);
}
}
private static int[] makeLeftRotation(int[] mainArr, int n, int k) {
int finalArr[]=new int[n];
int temp[]=new int[k];
int j=0;
for(int l=0;l<k;l++)
{
temp[l]=mainArr[l];
}
for(int i=0;i<n;i++){
if(k<n){
finalArr[i]=mainArr[k];
k=k+1;

}else
{
finalArr[i]=temp[j];
j=j+1;
}
}
return finalArr;
}

}

Sample Output:

Enter the arrays length: 

6
Enter the no of rotation needed.. 

3
1
2
3
4
5
6
After rotations: 4
After rotations: 5
After rotations: 6
After rotations: 1
After rotations: 2
After rotations: 3


Wednesday, 16 August 2017

Write a program in JAVA to print EVEN and ODD numbers within a range using multithreading.

To solve this problem we will be using one volatile variable as the variable will be shared between multiple threads.

We will have two threads even and odd. The logic is when even thread is executing odd thread will be suspended.

Suppose the Given input is: 10 
so output would be:
Odd Thread: 1
Even Thread: 2
Odd Thread: 3
Even Thread: 4
Odd Thread: 5
Even Thread: 6
Odd Thread: 7
Even Thread: 8
Odd Thread: 9
Even Thread: 10


Implemented Code:

 public class ThreadEvenOdd extends Thread{
    //Volatile keyword as this variable is going to be shared between multiple threads
    public volatile static int i=1;
    public Object lock;
    public ThreadEvenOdd(Object ob)
    {
        this.lock=ob;
    }
    public static void main(String[] args) {
        //Createing two threads even and Odd.
        Object object=new Object();
        ThreadEvenOdd even=new ThreadEvenOdd(object);
        ThreadEvenOdd odd=new ThreadEvenOdd(object);
        even.setName("Even Thread");
        odd.setName("Odd Thread");
        even.start();
        odd.start();      
    }
    @Override
    public void run()
    {
        while(i<=10)
        {
            if(i%2==0 && Thread.currentThread().getName().equalsIgnoreCase("Even Thread"))
            {
                synchronized(lock)
                {
                    System.out.println(Thread.currentThread().getName()+": "+i);
                    i++;
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            if(i%2==1 && Thread.currentThread().getName().equalsIgnoreCase("Odd Thread"))
            {
                synchronized(lock)
                {
                    System.out.println(Thread.currentThread().getName() + ": "+i);
                    i++;
                    lock.notify();
                }
            }
        }
    }
}
 



Monday, 14 August 2017

Divide two integers without using multiplication, division and mod operator

You are given one Dividend and Divisor. You need to find out the Quotient without using multiplication, division and mod operator.

For example :
Dividend=20 and Divisor=5 then Quotient=4
if Dividend=21 and Divisor=5, then Quotient=4

Sample code:

public class DivideTwoInt {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.println("Enter Integer to Dividend:  \n");
        int dividend=in.nextInt();
        System.out.println("Enter Divisor: \n");
        int divisor=in.nextInt();
        int count=checkDividend(dividend,divisor);
        System.out.println("Result is: "+count);

    }

    private static int checkDividend(int dividend, int divisor) {
        if(dividend==divisor)
            return 1;      
        if(dividend==0)
            return 0;
        if(divisor==0)
            return -1;
        int count=0;
        while(dividend>=divisor)
        {
            dividend=dividend-divisor;
            count=count+1;
        }
        return count;
    }
}



Sample Output 1:

Enter Integer to Dividend: 
20
Enter Divisor:
5
Result is: 4 


Sample output 2:

Enter Integer to Dividend: 
26
Enter Divisor:
5
Result is: 5

Write a program in JAVA where the sum of two elements of an array indices a specific target.

Another tricky question for java job seekers. You are given an array and a target element. You have to find out the sum of two elements which is equal to the specific target.

We will solve this approach by using Map. Time complexity would be O(n).

Sample Input:

Given array ={2,7,11,15};
Target element= 9
Output would be : 2 & 7.


Code:

public class SumOfTwoTarget {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
       
        int nums[]={2,7,11,15};
        Scanner in=new Scanner(System.in);
        System.out.println("Please enter the target: \n");
        int target=in.nextInt();
        checkTargetExist(nums,target);

    }
// Logic is substract each element of that array from target and assign it to a variable called element.
//If that element is present in the map, then return that key else add the array element in map and continue. 


    private static void checkTargetExist(int[] nums, int target) {
        Map<Integer, Integer> map=new HashMap<>();
        for(int i=0;i<nums.length;i++)
        {
            int element=target-nums[i];
            if(map.containsKey(element))
            {
                System.out.println("Target is present: values are: "+ map.get(element)+ " = "+i);
                return;
            }
            map.put(nums[i],i);
        }
        System.out.println("Sorry: Target is not present");
    }
}



Sample Output:

Please enter the target:
9
Target is present: values are: 0 = 1
 

Sunday, 13 August 2017

Write a program to find out the longest palindrome of a given String in JAVA

This is very tricky java interview questions. This question has been asked  in almost every product based company.

This problem can be asked in different ways like "find out no of palindromes of a given String"

Logic is pretty simple here. We will check every substring from start and end index. If the substring is palindrome then store it somewhere and check other substrings as well.

 So if the given input is "abcdcbaaaaaabccccba", then longest palindrome would be "cbaaaaaabc"

Sample Code:

/**
 * 
 * @author Sourin
 * 
 * This class is used to find out the longest palindrome of a given string. Logic is pretty simple, everytime 
 * we will pull out start and end index and check that is palindrome or not, if its palindrome store it somewhere and check the other substrings.
 *
 */
public class LongestPalindrome {
public static void main(String[] args) {
String palindrome="abcdcbaaaaaabccccba";
String longestPalindrome2=checkLongestPalindrome(palindrome);
System.out.println("Longest Palindrome is: "+ longestPalindrome2);
}
public static String checkLongestPalindrome(String palindrome)
{
String longestPalindrome="";
for(int i=0;i<palindrome.length();i++)
{
for(int j=palindrome.length()-1;j!=i;j--)
{
if(isPalindrome(palindrome.substring(i,j+1)))//check whether given string is palindrome or not.
{
if(palindrome.substring(i,j+1).length()>longestPalindrome.length())
{
longestPalindrome=palindrome.substring(i,j+1);
}
}
}
}
return longestPalindrome;
}
public static boolean isPalindrome(String ptest)
{
int k=ptest.length()-1;
for(int i=0;i<ptest.length()/2;i++)
{
if(ptest.charAt(i)!=ptest.charAt(k)){
return false;
}
k--;
}
return true;
}

}


Sample Output:


Longest Palindrome is: cbaaaaaabc





Write a program in java to do addition between two Linked List

This is one of the most common and tricky question in JAVA interview. I have faced this question during my interview with Nokia R&D.

We have two Linked Lists L1 and L2 having same or different size. We need to print the output.

Sample example1,
LinkedList l1: 4-->5-->3

LinkedList l2: 4-->5-->2

Output should be:
LinkedList l3: 8-->0-->6

Sample example2:

LinkedList l1: 4-->5-->3-->6

LinkedList l2: 4-->5-->2

Output:

LinkedList l3: 8-->0-->6-->6

Sample Code:

public class LinkListAddition {
public static void main(String[] args) {
LinkedList<Integer> linkList1=new LinkedList<>();
LinkedList<Integer> linkedList2=new LinkedList<>();
linkList1.add(2);/* adding values into the link lists*/ 
linkList1.add(4);
linkList1.add(3);
linkedList2.add(5);
linkedList2.add(6);
linkedList2.add(4);
linkedList2.add(8);
int carry=0;
Iterator<Integer> it1=linkList1.iterator();
Iterator<Integer> it2=linkedList2.iterator();
LinkedList< Integer> finalList=new LinkedList<>();
// Iterate through LinkedList 
while(it1.hasNext() || it2.hasNext())
{
int i=0;
int x=(it1.hasNext()?it1.next():0);
int y=(it2.hasNext()?it2.next():0);
int sum=x+y+carry;
if(sum>=10)
{
carry=sum/10;
finalList.add(sum%10);
}
else
{
finalList.add(sum%10);
carry=0;
}
i=i+1;
}
System.out.println("Lined List1: "+linkList1+" Linked List 2: "+ linkedList2 );
System.out.println("Output below:");
Iterator<Integer> it3=finalList.iterator();
while(it3.hasNext())
{
System.out.println("=>"+it3.next());
}
}
}


Sample Output:

Lined List1: [2, 4, 3] Linked List 2: [5, 6, 4, 8]
Output below:
=>7
=>0
=>8
=>8


Use of Lamda Expression and Functional Interface in JAVA 8

In this blog, we are going to discuss one of the most important features of JAVA 8 which is Lamda Expression and Functional Interface. A...