Tuesday, February 13, 2018

java questions


  • Given a binary tree, how to get the sum of vertical lines.
tip: try to find a solution with  linear time computation. Use a HashMap to store the sums.
  • Given a multi-million nodes linked List, how to get the value of the Nth node counting from the tail.  
tip: use 2 pointers and save an iteration
  • Implement a HashMap with TTL.
tip: override HashMap
  • Given a n X n matrix: find the count of the number chains, for example, the following matrix have 2 number chains. Also find the length of the longest chain, for example, the following matrix have max length 7.
1 2 3 0 0 0
0 0 4 5 0 0
0 0 0 6 0 0
0 1 0 7 0 0
0 2 0 0 0 0
0 3 4 0 0 0

tip: Map union and DFS
  • Given a nXn matrix, find the count of connected areas, for example the following matrix have 2 connected areas.

1 2 3 0 0 0
0 2 4 5 0 0
0 5 0 6 0 0
0 0 0 7 0 0
0 2 0 0 0 0
9 3 4 0 0 0

tip: Map union
  • write a java class that handles bank account deposit, withdraw and sum.
tip: consider 3 tier web application, this code could run in multiple app VMs.
  • write a function that returns if two words have the same characters. For example: func("file", "lief") should return true.
tip: HashMap
  •  A file looks like the following, the first column is the name, the second column is the versions. Read the file in and order the records by the versions.
aafdfad   12.34.1
dfadfadfadf     13.7.90
adfadfadfad   1.2.5.8
dfadfadf         9.0.33

tip: consider library quality code, edge conditions and unit tests.
  • A new IOT thermometer is invented and selling to general public, it is low power, low memory device. Design a system that updates its firmware.
tip: consider board type, micro OS, httpClient, geographically distributed update, selective update, failed update recover, cloud storage, log report, error report, batched roll out, pilot deploy, black out handle, oob handle, traffic zip etc.
  • Design a web application that takes start date, end date and city, returns the prices for hotels.
tip: consider thread pool, rest services, factory design pattern, future with timeout, third party content cache, scheduledThreadPool, periodic update, load balancer, database row lock, input/output validation etc.
  • Try to give an implementation of cloud storage system.
tip: hypervisor, unix file system or NoSQL, blob, item Id, global read-only but regional write, data center ETL, eventually consistent, object serialization and deserialization.
  • Design a program to output the percentage of english, Thai, French etc. words in an article.
tip: character frequency statistics
  • A program read millions of time ordered records through a third party api. Due to number round issue, the last few records returned from the third party api are not stable. How to work around this inacuracy in the program. 
tip: understand how the round issue happen and took more records so that the round issue caused inaccruacy will fall within the range. 
  • Design a program that downloads and parses logs to generate events.
tip: through what api the logs are downloaded, why choose rest/soap/http/raw socket, AAA, how to parse, generate event, blocking queue, database update, integrate, program monitoring, log, deployment, what actions will be triggered by certain events, how event flow at back end, inter process communication, etc.
Continue Reading »

Phone interview with SecureWork

A draft dated back at 2009

Just have a phone interview with the SecureWork for a senior java developer position.
The interview style is straight to the point.
Securework: hi, how are your doing tody?
Me: I'm doing well, thank you.
Securework: So the projects we will actually do is ... Now, I will ask you some questions about java to see if you are a good fit.
SecureWork: What's a abstract class?
Me: blablabla.
SecureWork: Ok. In what situation we prefer interface instead of abstract class?
Me: blablabla.
SecureWork: Ok. What is static Class?
Me: blablabla.

The interview going like this for half an hour, all aspects of java are asked. I guess he must have a standard question lists at hand and was keep scoring. The following is the questions I remember.

What is volatile variables?
What is keyword final?
What is keyword finally?
What is keyword static?
Explain auto-boxing.
Can I call a constructor through another constructor?
Can I call method of the super class?
What's the difference between sleep and wait?
In a multi-threading environment, how can you prevent methods to interfering each other?
Can you explain garbage collector?
When an object get garbage collected?
Will an object get garbage collected once it go out of scope?
Will garbage collection prevent memory outrage?
Can you give me an example of memory leakage in java programming?
What's the difference between the handeled and un-handeled Exceptions?
What's the differece between List and Set?
When we use LinkedList instead of Array?
When we use Array instead of LinkedList?
Please explain serilization?
What function you call to make serialization happen?
What's the difference between String and StringBuffer?
What's the difference between InputStream, OutputStream and PrintWriter, PrintReader?
Explain the keyword transient.
What's the difference between stack and queue?
When we use HashMap, and we we use TreeMap?
What is the Generic?
Give an example when you should use generic.
...
SecureWorks: So, I will ask some questions on linux. I have two very large files on two machines. The link between the two machines is very slow. Now I want to compare the two files in a short time, how will you do it?
Me: blablabla.

SecureWorks: Have you worked on database before?
Me: yes, blablabla.

SecureWorks: I will gonna ask you a few questions.
What is an index?
What's the difference between inner join and outer join?

SecureWorks: Now a design question. I have a webserver with heavy traffic. The user submits a word and the system looks up the dictionary and returns the explanation. We want achieve the best performance without too much cost. How will you go for it?

Then it is the interactive disscussion.

Finally, he stopped asking questions and began to introduce the projects they are doing recently and the agile developing strategy they are using for the projects.
He then asked my salary expectation and avialability for onsite interview next week.

I asked him what kind of questions I should prepare. He suggest me to put emphasis on algorithms.

The phone interviw lasts for about 1 hour. Continue Reading »

Wednesday, November 18, 2009

Core Java interview questions with Code Example

Question: How could Java classes direct program messages to the system console, but error messages, say to a file?

Answer: The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:


import java.io.*;

public class HelloWorld {
public static void main(String[] args) {
try {
PrintStream st = new PrintStream(new FileOutputStream("test.txt"));
System.setOut(st);
System.setErr(st);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}


Question: Explain the usage of the keyword transient?

Answer: Serilization is the process of making the object's state persistent. That means the state of the object is converted into stream of bytes and stored in a file. In the same way we can use the de-serilization concept to bring back the object's state from bytes. Sometimes serialization is necessary. For example, when we transmit objects through network, we want them to be consistent, therefore these objects have to be sterilizable,

On the other hand, we don't want the value of some member variable to be sterilizable, for instance, the password, then we use the keyword transient. When the class will be de-serialized, the transient variable will be initialized to 0 or null.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Logon implements Serializable {
private transient String password;

public Logon(String pwd) {
password = pwd;
}

public String toString() {
return password;
}

public static void main(String[] args) throws Exception {
Logon a = new Logon("hello_world");
System.out.println("logon a = " + a);
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
"Logon.out"));
o.writeObject(a);
o.close();
Thread.sleep(1000); // Delay for 1 second
// Now get them back:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"Logon.out"));
System.out.println("Recovering object at after 1 second");
a = (Logon) in.readObject();
System.out.println("logon a = " + a);
}
}


The output of the above example will be:

logon a = hello_world
Recovering object at after 1 second
logon a = null
Continue Reading »

Tuesday, November 17, 2009

Linux Commands - Hardware

* uname - print the OS information. "uname -a" display kernel-name, nodename, kernel-release, kernel version, machine, processor, hardware-platform, and operating system.
* dmesg - print comprehensive kernel and driver messages. For example, "dmesg >> file_to_mail_out.txt" output the information to a file for future trouble-shooting.
* top - display the system resources usage, and the updating processes.
* free - check memory usage.
* swapon - manage swap file or partition. "swapon -s" displays a summary of the swap usage.
* vmstat - display virtue memory information.
* lsof - list all the open files, sockets and pipes.
* tty - print the file name of the terminal connected to standard input.

* fdisk - manage disk partition. "fdisk -l" displays partition table.
* cfdisk - a easier progrom based on fdisk.
* fdformat - low-level format a floppy disk.

* eject - eject removable media.
* mount - unix file system is arranged in one big tree. mount attaches the file system found in some device into the big tree. "mount /dev/cdrom" mount the iso9660 file system found on the CDROM.
* unmount - unix file system is arranged in one big tree. unmount detaches the file system found in some device from the big tree. "unmount ./isoimage" unmount the iso9660 file system found on the file isoimage.

* import - "import screenshots" take a screen shots from x-window, save it to a file screenshots.

* ifconfig - displays the network interfaces.
* ifup - "ifup eth1" brings up a network interface eth1.
* ifdown - brings down a network interface.

* lpr - "lpr file.txt" sent the file.txt to default printer.
* lprm - remove the current printing job.
* pr - preformat a file for printing. "pr | lpr file.txt" Continue Reading »

Monday, November 16, 2009

Linux Commands - Programming

* cksum - calculate the check sum of a file, used to verify if two files are identical. Example: "cksum file1.txt" returns a number as the finger print of the file1.txt.

* echo - "echo $PATH" displays the value of environment variable PATH.
* env - displays all environment variable.
* export - write a variable to harddis. Example: "export MYVAR=$HOME" assigns the value of HOME to MYVAR, then set MYVAR as an environment variable.
* declare - declare variables and give them attributes. Example: "declare MYVAR=$HOME" assigns the value of HOME TO MYVAR, but does NOT set MYVAR as environment variable.
* read - read input from standard input, assign it to a variable. Example: "read newvar", input a value for newval, then "echo $newvar".
* sleep - delay for a some time. Example: "sleep 2" delay 2 seconds.

* alias - allow users to create abbreviations for complex commands. Example: "alias" displays all the existing aliases. Example: "alias mycmd="pwd" "
* unalias - delete an alias. Example: "unalias mycmd".
* nohup - run a command immune to hungups. Example: "nohup ls" run the command ls, write the output to file nohup.out.
* tee - "ls | tee file.out" this command display the output of command ls at standard output, while write them to the file.out. "ls >> file.out" won't display the output at standard output.
* sed - search and replace patterns in a file. Example: sed 's/my/your/g' afile.txt --this command substitute all "my" to "your" in the afile.txt.
* cut - divide a file into several parts. Example: "cut -d, -f1,3 sample.txt" divide lines by delimiter :, then output the first and third columns.
* sort - sort text files.
* paste - merge lines of files.
* split - split a file into many parts. Example: "split -b 1024 example.data new" split example.data into file newaa, newab, newac... each file have 1024 byte.
* vi - text editor.

* top - display the system resources statistics, and the updating processes.
* ps - display the running processes. "ps -A" displays all the running processes.
* kill - stop a process from running. "kill -9 3214" stops the process with id 3214 immediately.

* watch - execute a program periodically. Example: "watch -n 5 free" execute command free every 5 second.
* crontab - schedule tasks running periodically. Example: "crontab -l" list all the scheduled tasks for the current user. "crontab -e" edit the scheduler. For example, a task record could be "2 12 * * 5 /sbin/ping -c 1 www.google.com >> /dev/null", which means, ping google every 2 minutes at 12 o'clock on every friday. "crontab -d" delete all the scheduled tasks for the current user.

* chkconfig - control services. "chkconfig" displays the states of all the system services. "chkconfig sshd on" turn on the ssh service. Continue Reading »

Linux Commands - network

* vncpasswd - create a passwd for the vnc server.
* vncserver - create x-window display so that vncclient can remote login. Example: "vncserver :10 -geometry 1280x960" create a display :10 with size 1280x960. "vncserver -kill :10" stops the display :10.
* ftp - connect to a ftp server and is useful to manage your webpage hosting site. Example."ftp youracount.x10hosting.com".
* telnet - remote login to a host, not secure, use ssh instead.
* ssh - open an ssh session on a remote host. Example: "ssh guy@192.168.1.100" will login host 192.168.1.100 with user guy.
* scp - copy files from/to remote host using ssh. Example: "scp guy@192.168.1.100:test.txt /some/local/directory/" will copy file test.txt from site 192.168.1.100 to local machine.
* wget - Retrieve web pages or files via HTTP, HTTPS or FTP. Example: "wget http://www.google.com/index.html" will download the webpage index.html from google site.

* netstat - powerful network debug tool. Example: "netstat" displays all sockets. "netstat -r" displays routing table. "netstat -s" displays summary of protocols.
* ping - ping a remote host. Example: "ping -c 3 www.google.com" send 3 ping packets to google.
* traceroute - trace the route to a remote host. Example "traceroute www.google.com" will find all the router hops to google.
* iptables - administration tool for IPv4 packets filtering and NAT. Exmple: "iptables -l" list all rules for all chains.

* write - send message to a user loging into the machine. Example: "send guy" will open a sending box to pass a message to user guy. Control + D to close the message window.
* mail - send smtp mail. You should have a MTA such as postfix installed on your host in order to send mail. Example: "echo This will go into the body of the mail. | mail -s “Hello world” you@youremailid.com".

* hostname - display or set the host name for local machine.
* host - simple dns loop up. Example: "host www.google.com" get the ip address of google. "host 204.228.150.3" reverse loop up the domain for ip address.
* dig - detailed dns look up. Example: "dig kl2217.x10hosting.com" shows the A, CNAME, NS records of the dns loopup. "dig kl2217.x10hosting.com MX" shows the mail server loopup records.
* nslookup - interactive dns look up tool. Continue Reading »

Linux Commands - system administration

* su - log into root account.
* df - quick check for the disk space. "df -h -T" -h let output human readable, -T shows the file system type.
* du - quick check for file size. "du -h" shows the size of folders and files under current directory in a more readable format.
* finger - check who is on the system. fingure followed by user id shows detail history of a user.
* passwd - change the passwd of the current user. type in passwd then enter, you will be asked for old password then new password.
* dd - disk duplicate. "dd if=/dev/hdb1 of=/backup/", if stands for input file, of stands for output file.
* shutdown - shutdown the system. -h flag means halt, -r indicates reboot. For example "shutdown -h +120" will put the system into hibernate after 120 min.
* tar - zip and unzip files or directory. "tar cvfz tarball.tar.gz ./directory/" archive and compress the directory "dir" into file "tarball.tar.gz", "tar xvf tarball.tar.gz" unzip it. c means create new, x means untar, v means berbose, f means file.
* chmod - change file permission. "chmod 777 filename" give read, write, execute permission to owner, group and world. 7 = 4 + 2 + 1 = r + w + x.
* chown - change file's owner. "chown me file1" change file1's owner to "me".
* chgrp - change file's group. "chown users file1" changes file1's group to "users".
* id - print user and group id.
* groups - view the groups a user belongs to. "groups root" display all the groups root belongs to.
* groupadd - create new group. "groupadd mygroup" create a new group mygroup.
* groupmod - modify a group. "groupmod -n testgroup mygroup" change the name of mygroup to testgroup.
* groupdel - delete a group. "groupdel testgroup" delete the group testgroup.
* useradd - add a user. "useradd -g mygroup myuser" add the user myuser to group mygroup.
* usermod - modify a user. "usermod -g users myuser" change the group of myuser to users.
* userdel - delete a user. "userdel myuser" delete the user myuser. Continue Reading »