Friday, April 21, 2017

Amazon Interview Question:Check if a string can be obtained by rotating another string 2 places in Java

Given two strings, the task is to find if a string can be obtained by rotating another string two places.

Input : string1 = "amazon"
        string2 = "azonam"  // rotated anti-clockwise
Output : Yes

Input : string1 = "amazon"
        string2 = "onamaz"  // rotated clockwise
Output : Yes


Solution:

1- There can be only two cases:

    a) Clockwise rotated
    b) Anti-clockwise rotated

2- If clockwise rotated that means elements
   are shifted in right.
   So, check if a substring[2.... len-1] of
   string2 when concatenated with substring[0,1]
   of string2 is equal to string1. Then, return true.

3- Else, check if it is rotated anti-clockwise
   that means elements are shifted to left.
   So, check if concatenation of substring[len-2, len-1]
   with substring[0....len-3] makes it equals to
   string1. Then return true.

4- Else, return false.

Sample Code:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class RotatingString {

/**
* @param args
*/
public static void main(String[] args) {

  String str1 = "amazon";
  String str2 = "azonam";

   isRotated(str1, str2) ;

}

public static boolean isRotated(String str1, String str2)
{
String s = str1 + str2;
if(s.contains(str2))
return true;

else

return false;
}

}


Output: Yes




All about Java Constructors Interview Questions and Answers

What is a Constructor?

Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation.

What is Copy Constructor in Java?

Like C++, Java also supports copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own.

To copy the values of one object into another in java, you can use:
     
  • Assigning the values of one object into another
  • clone() method of Object class
  • Constructors
What is Constructor Chaining ?

Constructor Chaining is a basically, calling another constructor from one constructor. this() is used to call same class constructor where as super() is used to call super class constructor.

Sample Code:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class ConstructorChaining {


public ConstructorChaining()
{
this(5);
               System.out.println("The Default constructor");
        
}
public ConstructorChaining(int x) 
{
this(5, 15);
               System.out.println(x);
}

public ConstructorChaining(int i, int j)
{
System.out.println(i * j);
}

public static void main(String[] args) 
{
// TODO Auto-generated method stub
       new ConstructorChaining();
}

}

Output:

75
5
The Default constructor

Can we call sub class constructor from super class constructor?

No.There is no way you can do this in java.


What happens if you keep a return type for a constructor?

Ideally, Constructor can not have a return type By definition, if a method has a return type, it’s not a constructor.(JLS8.8 Declaration) It will be treated as a normal method. But compiler gives a warning saying that method has a constructor name.

Example:

public class ConstructorChaining {


int ConstructorChaining()
{
            return 0;
        }
public static void main(String[] args) 
{
            new ConstructorChaining();
}

}

What is the difference between argument constructor and default Constructor?

Ans:

If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.


What are private constructors and where are they used?

Ans:

Like any method we can provide access specifier to the constructor. If it’s made private, then it can only be accessed inside the class.

Lets take example, we use private constructor:

Internal Constructor chaining
Singleton class design pattern

When do we need Constructor Overloading?

Ans:

Sometimes there is a need of initializing an object in different ways. This can be done using constructor overloading. Different constructors can do different work by implementing different line of codes and are called based on the type and no of parameters passed.
According to the situation , a constructor is called with specific number of parameters among overloaded constructors.

Do we have destructors in Java?

Ans:

No, Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor.





Monday, April 17, 2017

Amazon Interview Question asked: Number of subsequences of the form a^i b^j c^k solution in Java

Amazon Interview Question asked:Number of subsequences of the form a^i b^j c^k

Given a string, count number of subsequences of the form aibjck, where i >= 1, j >=1 and k >= 1.

Note: Two subsequences are considered different if the set of array indexes picked for the 2 subsequences are different.

Examples:

Input  : abbc
Output : 3
Subsequences are abc, abc and abbc

Input  : abcabc
Output : 7
Subsequences are abc, abc, abbc, aabc
abcc, abc and abc

Solution:

We traverse given string. For every character encounter, we do following:

1) Initialize counts of different subsequences caused by different combination of ‘a’. Let this count be aCount.

2) Initialize counts of different subsequences caused by different combination of ‘b’. Let this count be bCount.

3) Initialize counts of different subsequences caused by different combination of ‘c’. Let this count be cCount.

4) Traverse all characters of given string. Do following for current character s[i]
    If current character is ‘a’, then there are following possibilities :

    a) Current character begins a new subsequence.
    b) Current character is part of aCount subsequences.
    c) Current character is not part of aCount subsequences.
    Therefore we do aCount = (1 + 2 * aCount);

    If current character is ‘b’, then there are following possibilities :

    a) Current character begins a new subsequence of b’s with aCount subsequences.
    b) Current character is part of bCount subsequences.
    c) Current character is not part of bCount subsequences.
    Therefore we do bCount = (aCount + 2 * bCount);

    If current character is ‘c’, then there are following possibilities :

    a) Current character begins a new subsequence of c’s with bCount subsequences.
    b) Current character is part of cCount subsequences.
    c) Current character is not part of cCount subsequences.
    Therefore we do cCount = (bCount + 2 * cCount);

5) Finally we return cCount;


Sample Code:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class NumberOfSubseqences
{

public static int countSubsequences(String s)
{
   int aCount = 0;
   int bCount = 0;
   int cCount = 0;

   for (int i=0; i<s.length(); i++)
   {
       if (s.charAt(i) == 'a')
           aCount = (1 + 2 * aCount);

       else if (s.charAt(i) == 'b')
           bCount = (aCount + 2 * bCount);

       else if (s.charAt(i) == 'c')
           cCount = (bCount + 2 * cCount);
   }
   return cCount;
}


public static void main(String[] args)
{
String s = "abbc";
countSubsequences(s);
}


}

Output: 3

Time Complexity would be O(n).


Thursday, April 13, 2017

Multiples of 3 and 5 without using % operator

Write a short program that prints each number from 1 to n on a new line.

For each multiple of 3, print “Multiple of 3” instead of the number.

For each multiple of 5, print “Multiple of 5” instead of the number.

For numbers which are multiples of both 3 and 5, print “Multiple of 3. Multiple of 5.” instead of the number.


Examples:

Input  : 15 

Output : 1
         2
         Multiple of 3.
         4
         Multiple of 5.
         Multiple of 3.
         7
         8
         Multiple of 3.
         Multiple of 5.
         11
         Multiple of 3.
         13
         14
         Multiple of 3. Multiple of 5.
 
 
Solution:


The solution is simple. we just have to iterate from 1 to n and have to track the multiples of 3 and 5 by adding 3 and 5 to the current multiple.If the current number you get matches with a multiple then we update our result accordingly.  

Sample Code:

/**
 * @author Abhinaw.Tripathi
 *
 */
public class MultipleOfThreeAndFive 
{

public static void findMultiple(int n)
{
int a = 3;  
        int b = 5;  
        for (int i=1; i<=n; i++)
        {
            String s = "";
 
           
            if (i==a)
            {
                a = a + 3;  
                s = s + "Multiple of 3. ";
            }
 
           
            if (i==b)
            {
                b = b+5;  
                s = s + "Multiple of 5.";
            }
 
            if (s == "")
                System.out.println(i);
            else  System.out.println(s);
        }
}
public static void main(String[] args)
    {

        findMultiple(20);
}

}


Output:

1
2
Multiple of 3. 
4
Multiple of 5.
Multiple of 3. 
7
8
Multiple of 3. 
Multiple of 5.
11
Multiple of 3. 
13
14
Multiple of 3. Multiple of 5.
16
17
Multiple of 3. 
19
Multiple of 5.