Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

June 23, 2010

Amazon telephonic interview ques

1. Write an efficient algo to find longest recurring substring in a string e.g. in banana, it would be 'ana'


Ans : We can use suffix trees to implement this. I will post the exact solution soon

2. Write a function to find intersection of two strings. i.e. characters common to the strings.

For this, the most efficient solution would be to use 26 bits .. one for each character and put zero in all and then wen u encounter a character, just make the corresponding bit 1. For this, we ll need to traverse both the strings only once ands the extra memory that would be required would only be 26 bits :) O(n) solution

Inefficient O(n^2) Method of finding Largest Recurring Substring in a string

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
* @author Pragya Rawal
*/
public class LargestSubstring {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String : ");
try {
String input = br.readLine();
LargestSubstring str = new LargestSubstring();
String largestSubstr = str.getLargestSubstr(input);
if (largestSubstr != null) {
System.out.println("Largest Recurring substring is : "
+ largestSubstr);
}
} catch (IOException e) {
e.printStackTrace();
}

}

public String getLargestSubstr(String input) {
if (null == input || input.length() == 0) {
System.out.println("Invalid / Empty string ...");
return null;
} else {
int length = input.length();
int subStrLen = 0;
String longestSubStr = "";
String currentStr = "";
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
int k = i;
int l = j;
while ((k < length) && (l < length) &&(input.charAt(k) == input.charAt(l)) ) {
currentStr += input.charAt(k);
k++;
l++;
subStrLen++;
}
if (longestSubStr.length() < currentStr.length()) {
longestSubStr = currentStr;
}
currentStr = "";
}

}
return longestSubStr;
}

}
}

June 22, 2010

Program(s) for finding power of a number

First, an interactive solution: (raising a to the power of b)

public double Power(double a, int b) {
if (b<=0) return 0; // we want a positive integer for the exponent
else {
double c=1;
for (int i=0; i c*=a;
}
return c;
}
}


Very easy and linear. You start from one and go on multiplying c by a so c is respectively 1, a, a^2, a^3, ... a^b.
When done, you return c. This one takes linear time.

Second, a recursive solution:

public double Power(double a, int b) {
if (b<=0) return 0;
else if (b==1) return a;
else {
return a*Power(a,b-1);
}
}


This is also an easy one. What we do here? Simple: we calculate a^b=a * a^(b-1). This is done by the recursion and takes linear time as well.

So, how can we beat these to slugs? We do this way.
Let me give you an example with b being a power of 2 (which is the easiest to understand).

Imagine you have to evaluate a^64. You could think this:

a^64 = c^32 where c=a^2
c^32 = d^16 where d=c^2
d^16 = e^8 where e=d^2
e^8 = f^4 where f=e^2
f^4 = g^2 where g=f^2
g^2 = g*g

This requires 6 operations. Using one of the two previous algorithms takes 64 operations! In fact 6=log64 (log is meant in base 2 obviously).

Now, things are different when b isn't a power of 2, but the algorithm is just a bit more complicated. Let's see an example again. We'll evaluate a^20.

a^20 = c^10 where c=a^2
c^10 = d^5 where d=c^2
d^5 = d * e^2 where e=d^2
e^2 = e*e

This requires 5 operations. Log16=4 and log32=5 so as you can see we have here 5=Ceiling(log20). This happens when b isn't a power of 2, but the cost of the entire algorithm doesn't grow that much and we can still say that it runs in logarithmic time (this is more true when b is a medium-big number).

private double Power(double a, int b) {
if (b<0) {
throw new ApplicationException("B must be a positive integer or zero");
}
if (b==0) return 1;
if (a==0) return 0;
if (b%2==0) {
return Power(a*a, b/2);
} else if (b%2==1) {
return a*Power(a*a,b/2);
}
return 0;
}


Another solution can be :
a^b = 10^(ln[10](a) * b)

Reference : http://www.osix.net/modules/article/?id=696

Details of retainAll() in Set interface

The Set interface contains a method 'retainAll()' which gives us the intersection of two sets.

Lets say we define a Set as : Set s = new HashSet();

HashSet class extends the abstract class AbstractSet , which in turn extends the abstract class AbstractCollection. The implementation of retainAll() is present in AbstractCollecction class.

This method Retains only the elements in this collection that are contained in the
specified collection (optional operation). In other words, removes
from this collection all of its elements that are not contained in the
specified collection.



This implementation iterates over this collection, checking each
element returned by the iterator in turn to see if it's contained
in the specified collection. If it's not so contained, it's removed
from this collection with the iterator's remove method.



Note that this implementation will throw an
UnsupportedOperationException if the iterator returned by the
iterator method does not implement the remove method
and this collection contains one or more elements not present in the
specified collection.

Clock Angle Problem : Amazon Ques

Clock angle problems relate two different measurements - angles and time. To answer the problem the relationship between the time shown (or an elapsed time) and the position of the hands (as given by an angle) has to be found.
A general approach to such problems is to consider the rate of change of the angle in degrees per minute. The hour hand of a normal 12-hour analogue clock turns 360 degrees in 12 hours. This is equivalent to 360 degrees in 720 minutes or 0.5 degrees per minute. The minute hand turns 360 degrees in 60 minutes or 6 degrees per minute.

Equation for the degrees on the hour hand

(0.5 degrees per minute on the hour hand) * (the time on the hour hand * 60 minutes per hour) + (0.5 degrees per minute on the minute hand) * (the time on the minute hand)

Equation for the degrees on the minute hand

(6 degrees per minute on the minute hand) * (the time on the minute hand)

'Example: The time is 5:24'
The degree on the hour hand is (0.5*5*60)+(0.5*24)=162 degrees
It could be also calculated as
Hour hand angle = total minutes / 2
In this case Hour hand angle = total minutes / 2 = ( (total hours * 60) + (total minutes) ) / 2 = ( (5 * 60) + 24 ) / 2 = 162 degrees
The degrees on the minute hand is 6*24=144 degrees

Minute handl angle = minutes * 6
Equation for the degrees between the hands

The angle between the hands can also be found using the formula cos-1(cos(5.5x)), where x=the number of minutes past noon. This will always give an angle between 0 and 180 degrees.

'Example: The time is 1:35'

1:35 is 1(60)+35=95 minutes past noon.
cos-1(cos(5.5*95))=cos-1(cos(522.5))=cos-1(-.95372)=162.5 degrees between the hands
Angle=mod(60H-11M)/2
where H= hours and M=minutes

When are hour and minute hands of a clock superimposed?

Hour and Minute hands are superimposed only when angle between them are 0. If hour and minute hands are superimposed at time h:m
0.5*60*h + 0.5*m = 6*m
m=(30/5.5)*h
for h varies from 0...11, clock hands are superimposed at 1:05.4545,2:10.90...12:00.

June 14, 2010

Class Loader methods : Why class loaders must delegate class loading

defineClass() : This method converts the array of bytes code an instance of the class.The class must be resolved before it can be used. THis is a final method. In this, an instance of class java.lang.Class is created and cached in the Class Loader so that the byte code can not change on the further requests to load the class. This method also checks that the given class name matches the class name in the byte code. Because this method is final, no custom class loader can change this behavior.


Q : Why class loaders must delegate class loading ?
As we know, a class loader must delegate the class loading(although a developer can override loadClass() and change this behavior). On one hand, if loading of system classes is not delegated, an application could provide malicious code for JDK classes and introduce a ton of problems. On the other hand, all classes at least extend java.lang.Object, and this class must be resolved, too. Thus the custom class loader has to load this class by itself, otherwise the load fails with a linkage error. These two facts imply that a custom class loader has to delegate class loading.

However,there are some loaders like the loader for web container defined in servlet specification, tries to load the class by itself before delegating.Nevertheless, some classes, such as java.*, javax.*, org.xml.sax.* and others, are delegated first to the parent.


As long as a Java developer does not deal with his or her own class loader, all of the classes are loaded by the bootstrap and system class loader, and there will never be a conflict. Thus, it seems that a class is defined only by the fully qualified class name. As soon as there are sibling class loaders -- neither a parent of the other -- a class type can be loaded multiple times with or without different byte code. The class loader also defines the visibility of a class type because any upcast checks against the class name as well as its class loaders.

To use the currency analogy, this is expressed by the fact that you can have several currencies in your wallet, but as soon as you want to use one, the cashier will check if your money is of the local currency. Still, you can carry these currencies in your pocket wherever you go, and likewise, you can carry around instances of classes even when they are unknown or not compatible in a particular class, as long as the class of the reference is compatible there. Luckily in Java, java.lang.Object is the superclass of all instances and is loaded by the BS, which is the parent of all class loaders no matter what. This means a reference of a class java.lang.Object is always compatible. I think of this as a "tunneling through" of classes from one compatible island to the next -- something that is very important in J2EE, as will be shown in a future installment.

June 13, 2010

'Extension' Class Loader

The extension framework makes use of the class-loading delegation mechanism. When the runtime environment needs to load a new class for an application, it looks for the class in the following locations, in order:
Bootstrap classes: the runtime classes in rt.jar, internationalization classes in i18n.jar, and others.
Installed extensions: classes in JAR files in the lib/ext directory of the JRE, and in the system-wide, platform-specific extension directory (such as /usr/jdk/packages/lib/ext on the SolarisTM Operating System, but note that use of this directory applies only to JavaTM 6 and later).
The class path: classes, including classes in JAR files, on paths specified by the system property java.class.path. If a JAR file on the class path has a manifest with the Class-Path attribute, JAR files specified by the Class-Path attribute will be searched also. By default, the java.class.path property's value is ., the current directory. You can change the value by using the -classpath or -cp command-line options, or setting the CLASSPATH environment variable. The command-line options override the setting of the CLASSPATH environment variable.
The precedence list tells you, for example, that the class path is searched only if a class to be loaded hasn't been found among the classes in rt.jar, i18n.jar or the installed extensions.

Unless your software instantiates its own class loaders for special purposes, you don't really need to know much more than to keep this precedence list in mind. In particular, you should be aware of any class name conflicts that might be present. For example, if you list a class on the class path, you'll get unexpected results if the runtime environment instead loads another class of the same name that it found in an installed extension.


Class Loaders - getClassLoader() method

There is a getClassLoder() method in the class java.lang.Class which tells us about the ClassLoader that loaded the class.

Below is the javaDoc for the same :

Returns the class loader for the class. Some implementations may use
null to represent the bootstrap class loader. This method will return
null in such implementations if this class was loaded by the bootstrap
class loader.

If a security manager is present, and the caller's class loader is
not null and the caller's class loader is not the same as or an ancestor of
the class loader for the class whose class loader is requested, then
this method calls the security manager's checkPermission
method with a RuntimePermission("getClassLoader")
permission to ensure it's ok to access the class loader for the class.

If this object
represents a primitive type or void, null is returned.

@return the class loader that loaded the class or interface
represented by this object.
@throws SecurityException
if a security manager exists and its
checkPermission method denies
access to the class loader for the class.
@see java.lang.ClassLoader
@see SecurityManager#checkPermission
@see java.lang.RuntimePermission

June 11, 2010

Around advice vs Before/ After Advice

MethodInterceptor provides the ability to do both berfore and after advices in one advice object:
public interface MethodInterceptor extends Interceptor {
Object invoke(MethodInvocation invocation) throws Throwable;
}
There are two important differences between the MethodInterceptor interface
and the previous two types of advice. First, the MethodInterceptor implementation
controls whether the target method is actually invoked. Invoking the target
method is done by calling MethodInvocation.proceed(). This is in contrast to
MethodBeforeAdvice, where the target method is always called unless you throw
an exception.
Second, MethodInterceptor gives you control over what object is returned. This
means you can return a completely different object than the one returned by proceed().
Remember, with AfterReturningAdvice you had access to the object being returned, but you could not return a different object. While MethodInterceptor
provides this added flexibility, you should use caution when returning a different
object than the one returned by the target method and only do so when necessary.

Advice in Spring AOP

Advice contains the logic of your aspect. So,when you create an advice object, you are writing the code that implements the
cross-cutting functionality. Also, remember that Spring’s joinpoint model is built
around method interception. This means that the Spring advice you write will be
woven into your application at different points around a method’s invocation.
Because there are several points during the execution of a method that Spring
can weave in advice, there are several different advice types.

Advice type Interface Description
Around org.aopalliance.intercept.MethodInterceptor Intercepts calls to the target
method
Before org.springframework.aop.BeforeAdvice Called before the target
method is invoked
After org.springframework.aop.AfterReturningAdvice Called after the target
method returns
Throws org.springframework.aop.ThrowsAdvice Called when target
method throws an
exception

Spring AOP

Spring does not create a proxied object until that proxied bean is needed by the
application. If you are using an ApplicationContext, the proxied objects will be
created when it loads all of the beans from the BeanFactory. Because Spring creates
proxies at runtime, you do not need a special compiler to use Spring’s AOP.
Spring generates proxied classes in two ways. If your target object implements
an interface(s) that exposes the required methods, Spring will use the JDK’s
java.lang.reflect.Proxy class. This class allows Spring to dynamically generate
a new class that implements the necessary interfaces, weave in any advice, and
proxy any calls to these interfaces to your target class.
If your target class does not implement an interface, Spring uses the CGLIB1
library to generate a subclass to your target class. When creating this subclass,
Spring weaves in advice and delegates calls to the subclass to your target class.
When using this type of proxy generation, you need to deploy all of the JAR files
in the lib/cglib directory of your Spring distribution with your application.
There are two important things to take note of when using this approach:
■ Creating a proxy with interfaces is favored over proxying classes, since this
leads to a more loosely coupled application. The ability to proxy classes is
provided so that legacy or third-party classes that do not implement interfaces
can still be advised. This approach should be taken as the exception,
not the rule.
■ Methods marked as final cannot be advised. Remember, Spring generates
a subclass to your target class. Any method that needs to be advised is overridden
and advice is woven in. This is not possible with final methods.

Spring implements AOP Alliance interfaces
The AOP Alliance is a joint project between several parties interested in implementing
AOP in Java. The AOP Alliance shares the same belief as Spring that AOP
can provide cleaner and easier solutions for Java enterprise applications than what
is currently offered by EJB. Their goal is to standardize Java’s AOP interface to provide
interoperability between various Java AOP implementations. This means that
AOP advice that implements their interfaces (as do some of Spring’s implementations)
will be reusable in any other AOP Alliance–compatible framework.
Spring only supports method joinpoints
As mentioned earlier, multiple joinpoint models are available through various
AOP implementations. Spring only supports method joinpoints. This is in contrast
to some other AOP frameworks, such as AspectJ and JBoss, which provide
field joinpoints as well. This prevents you from creating very fine-grained advice,
such as intercepting updates to an object’s field.
However, as Spring focuses on providing a framework for implementing J2EE
services, method interception should suit most, if not all, of your needs. Plus,
Spring’s philosophy is that field interception violates encapsulation. A fundamental
object-oriented concept is that objects initiate operations on themselves
and other objects through method calls. Having advice fired on field modification
as opposed to method invocation arguably violates this concept.

June 9, 2010

More about Internet Servers

POP3 is by far the most common type of incoming e‑mail server for personal e‑mail accounts. And SMTP is the only type of outgoing e‑mail server that works with Windows Mail, so you normally don’t even need to check the outgoing server type with your e‑mail provider. Practically all personal e‑mail accounts—with the exception of web-based e‑mail—use an SMTP server for outgoing e‑mail.

E‑mail server addresses usually have the same format. Most ISPs (named “myisp” in this example) have server addresses like this:

Incoming server: pop.myisp.com (or imap.myisp.com, if they use an IMAP server)

Outgoing server: smtp.myisp.com

You can usually substitute the name of your ISP in place of myisp in the example above. If this doesn’t work, check with your ISP. Questions about e‑mail server addresses are among the most common inquiries e‑mail providers get, so they usually have this information posted in the support section of their websites.

Here are server addresses for some of the most popular e‑mail services:

Yahoo!: pop.mail.yahoo.com (incoming) and smtp.mail.yahoo.com (outgoing)

AOL: imap.aol.com (incoming) and smtp.aol.com (outgoing)

Gmail: pop.gmail.com (incoming) and smtp.gmail.com (outgoing)

Finally, you must know whether your outgoing e‑mail server requires authentication, since there is a check box for this when you set up a new e‑mail account in Windows Mail. If you can’t find out the answer from your e‑mail provider, try sending a test message with the check box selected and another one with the check box cleared, to see which works.

E‑mail server types

Windows Mail supports three types of e‑mail servers.

Post Office Protocol 3 (POP3) servers. Most e‑mail services and ISPs use this type of server, especially for personal e‑mail accounts. They hold incoming e‑mail messages until you check your e‑mail, at which point they're transferred to your computer. Messages are typically deleted from the server when you check your e‑mail.

Internet Message Access Protocol (IMAP) servers. These servers let you work with e‑mail messages without downloading them to your computer first. You can preview, delete, and organize messages directly on the e‑mail server. Copies are stored on the server until you delete them. IMAP is commonly used for business e‑mail accounts.

Simple Mail Transfer Protocol (SMTP) servers. This outgoing mail server handles the sending of your e‑mail messages to the Internet. An SMTP server handles only the outgoing e‑mail, and is used in conjunction with a POP3 or IMAP incoming e‑mail server.

June 7, 2010

Simple java Program for sending mails

package com.abc;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendingEmail {
public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
{
boolean debug = false;

//Set the host smtp address
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
// props.put("mail.smtp.host", "smtp.mta"); // MS smtp
props.put("mail.smtp.host", "smtp.gmail.com"); // airtel smtp
props.put("mail.smtp.starttls.enable","true");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);

// create a message
Message msg = new MimeMessage(session);

// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);

InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);


// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");

// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
}

Main Class :


package com.abc;

import javax.mail.*;

public class SendMailMain {

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

SendingEmail sm = new SendingEmail();
String[] recep = {"zzzz.yyyy@yahoo.co.in"};
try{
sm.postMail(recep, "HI", "From ABC", "mmmm.nnnn@gmail.com");
}catch (MessagingException e) {
e.printStackTrace();
}
}

}


The idea behind this is that some SMTP servers (like gmail smtp) require authentication. So, you need to provide your credentials for them.
But for some SMTP servers (e.g. smtp.mta ) are open for all where in anyone can send mail from any id to any id, without any authentication required.


So, for the servers which requrie authentication,
u need to add the below code :


static class PopupAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("UserName", "Password");
}
}

This is extending abstract Authenticator class and overriding the getPasswordAuthentication() method.


Refer : http://forums.sun.com/thread.jspa?threadID=345884