Wednesday, December 30, 2009

Tricky question.....

Que: You have 2 arrays each containing a set of numbers. Write an
algorithm that gets the elements present in the first array and missing
from the second. It should have n complexity.


void fun(int a[], int b[], int N){
int max = a[0];
for(int i =0; i < N;i++)
if(max < a[i])
max = a[i];

int c[max]={0};
for(int i =0; i < N;i++)
c[a[i]]++;

for(int i =0; i < N;i++)
c[b[i]]--;

for(int i =0; i < N;i++)
if(c[a[i]]==1)
print a[i];
}

How to find median of a BST?

If the no of keys are odd, there will be only one median, if it is even there will be two median.
  • Execute two InOrder traversal, the first one runs as the double speed the second one. It means the first one visits two nodes while the second one visits one nodes. So when the first one finish traverse, the second one point the mid value!

Thursday, December 3, 2009

Creating Own exception class in java.

Note: Exception class must be inherited


class OutOfRange extends Exception{
String message;
OutOfRange(){
message = new String("Please Enter No's between 0 and 100");
}
String toStr(){
return message;
}
}

public class MainCls{
public static void main(String args[]){
int input;
String inputStr;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

inputStr = br.readLine();
input = Integer.parseInt(inputStr);

try{
if(input < 0 || input > 100)
throw new OutOfRange();
}
catch(OutOfRange e){
System.out.println(e.toStr());
}
//Rest of code...
}
}

Difference between compiler and Interpretor.

Interpreter
An interpreter reads the source code one instruction (a line) at a time, converts this line into machine code and executes it. The current machine code is then discarded and the next line is read. Examples of interpreters are Basic and script interpreters such as Tcl script, JavaScript etc.

Advantages
The advantage of this is it's simple and you can interrupt it while it is running, change the program and either continue or start again.

Disadvantages

Every line has to be translated every time it is executed, because of this interpreters is relatively slow.

Compiler
A compiler reads the whole source code and translates it into a complete machine code output as a new file(object file). This completely separates the source code from the executable file. Examples of compilers are Visual Basic, C, C++, C#, Fortran, Cobol, Ada, Pascal etc.

Advantages
Advantage of this is that the translation is done once only and as a separate process. The program that is run is already translated into machine code so is much faster in execution.

Disadvantages
The disadvantage is that you cannot change the program without going back to the original source code, editing that and recompiling.

Search Ranjeet's Blog