## Problem Statement

There are N strings. Each string’s length is no more than 2020 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurred previously.

Input Format

The first line contains N, the number of strings.
The next N lines each contain a string.
The N+2nd line contains Q, the number of queries.
The following Q lines each contain a query string.

Constraints

1N1000
1Q1000
1lengtof anstring20

Sample Input

4
aba
baba
aba
xzxb
3
aba
xzxb
ab

Sample Output

2
1
0

Explanation

Here, “aba” occurs twice, in the first and third string. The string “xzxb” occurs once in the fourth string, and “ab” does not occur at all.

## How to find nth highest integer value from a table?

For a Sample table

 name value a 1 b 3 c 5 d 2 e 0 f 7

If we want to find the nth highest integer value, then the SQL would be:

1. SELECT MIN(value) FROM (SELECT * FROM table ORDER BY value DESC)
2. WHERE ROWNUM <=2

## Combinations of a String

Problem:
Write an algorithm to print all possible combinations of characters in a string.

Solution:
Since we need to generate combinations, we can start with a single character and then continue to add a character to combinations we have seen so far.

Let’s use “XYZ” as an example.

public void buildTree(String input, StringBuffer output, int k)
{
for (int i = k; i < input.length(); i++)
{
output.append(input.charAt(i));
buildTree(input, output, i + 1);
output.deleteCharAt(output.length() - 1);
}
}

public static void main(String[] args){
buildTree("XYZ", new StringBuffer(), 0);
}

Dry Run just to give an idea:

X–>Y–>Z
–>Z–>Y

Y–>X–>Z
–>Z–>X

Z–>Y–>X
–>X–>Y

## Gold for 7 Days of Work Puzzle

Problem Statement:

You’ve got someone working for you for seven days and a gold bar to pay them. You must pay the worker for their work at the end of every day. If you are only allowed to make two breaks in the gold bar, how do you pay your worker?
(Assuming equal amount of work is done during each day thus requiring equal amount of pay for each day)

The trick is not to try and how to cut in such a way to make 7 equal pieces but rather to make transactions with the worker. Make two cuts on the gold bar such that you have the following sizes of bars.

1/7, 2/7 and 4/7.

 Day Pay Take Back Total Paid Amount Balance Amount 1 1/7 N/A 1/7 2/7, 4/7 2 2/7 1/7 2/7 1/7, 4/7 3 1/7 N/A 3/7 4/7 4 4/7 1/7, 2/7 4/7 2/7, 1/7 5 1/7 N/A 5/7 2/7 6 2/7 1/7 6/7 1/7 7 1/7 N/A 7/7 N/A

## Problem Statement

You have 25 horses, and you want to pick the fastest 3 horses out of those 25. Each race can have maximum of 5 horses at the same time. What is the minimum number of races required to find the 3 fastest horses without using a stopwatch?

## Solution

Let’s say that we have 5 races of 5 horses each, so each row in the table above represents a race.

 H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15 H16 H17 H18 H19 H20 H21 H22 H23 H24 H25

Let each row represent a race.

Step 1: Perform 5 races of each set.

Result:

 1st 2nd 3rd 4th 5th H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15 H16 H17 H18 H19 H20 H21 H22 H23 H24 H25

Step 2: Elimination by logical analysis:

• We can eliminate the slowest 2 horses in each group since those horses are definitely not in the top 3
• The 5 group leaders are not necessarily the 5 fastest horses, therefore race those 5 horses against each other (H1, H6, H11, H16, and H21) {Race 6}, Let’s say that the 3 fastest in that group are H1, H6, and H11 – automatically we can eliminate H16 and H21 since those 2 are definitely not in the top 3
• We can automatically eliminate all the horses that H16 and H21 competed against in the preliminary races as they were slower than H16 and H21
• We also know that H1 is the fastest horse in the group since he was the fastest horse out of the 5 group leaders
• if H6 and H11 are the 2nd and 3rd fastest in the group leaders, then we should be able to eliminate H8 since H6 raced against him and he was in 3rd place in that race
• We can also eliminate H12 and H13 since H11 was the 3rd fastest in the group leaders, and H12 and H13 were slower than H11
• This leaves us with the following horses to determine the 2nd and 3rd fastest horses:
 H2 H3 H6 H7 H11

Race the last Set {Race 7} to get the Top 2nd and 3rd racers with H1 as the fastest.

Total number of Races: 7

## Problem Statement:

There is a building of 100 floors  If an egg drops from the Nth floor or above it will break. If it’s dropped from any floor below, it will not break. You’re given 2 eggs.

Give an Algorithm to find N, while minimizing the number of drops for the worst case.

## Solution:

The Problem comes with a general equation as X(Max Number of floors) = n*n;

So in this case for example, X= 100 Floors( => n=10)

now use the value n to traverse. This means that drop the first egg from 10th floor, then 20th floor, then 30th and so on up to 90.

The floor from which it breaks, say 60th, then go back 10 floors and try each floor to find N.

After Floor 90, Start moving 1 by 1.

Worst case scenario:

eggs break at 99th floor.

Egg drops: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70 -> 80 -> 90 -> 91 -> 92 -> 93 -> 94 -> 95 -> 96 -> 97 -> 98 -> 99

Max Attempts: 18

## How to put a time restriction on a method in java?

I have a specific requirement where in I am calling a method and I want to get the response within a specific duration.
For example, I am trying to fetch the contents of a web-page.

If within 3 seconds, I get the response, its good, otherwise, I want to give a message to the user that internet is too slow.

Now, how do I do this?

You could make use of the ExecutorService and its timeout facilities. The idea is to execute the method you want to call in a different thread, and let the ExecutorService cancel it after a specific time. Here is a simple example, using two fixed threads. You’d have to adapt this to your needs.

Make a class MyTask implements Callable

package testapp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

private String name;
private long sleepTime;

public MyTask(String name, long sleepTime) {
this.name = name;
this.sleepTime = sleepTime;
}

public Void call() throws Exception {
return null;
}
}

Use this as is done here

public class ExecutorServiceTest {

public static void main(String[] args) throws InterruptedException {
System.out.println(new java.util.Date());
for (Future future : taskFutures) {
System.out.println("Done: " + future.isDone());
System.out.println("Cancelled: " + future.isCancelled());
}
System.out.println(new java.util.Date());

System.out.println("END");

}
}

## Comparable vs Comparator

There are many articles available on internet for this. But still I would write something about it.

### What when and why?

A Comparable class is a class, which can be compared with the objects of its own type. Let us take an example of a book.

public class Book implements Comparable {
String title;
int    isbn;

Book(String title, int isbn) {
this.title = title;
this.isbn  = isbn;
}
/* This method will be the default method used
to sort Book objects in a list or Array */
public int compareTo(Object object) {
// It should throw NullPointerException if object passed is null
if (object==null)
{
throw new NullPointerException("compareTo: Argument passed is null");
}
Book other = (Book) object;
if (this.title.equals(other.title)) {
return this.isbn - other.isbn;
}
return this.title.compareTo(other.title);
}
}

The moment your class implements Comparable, you can then use

Collections.sort(list);

Using this you can sort your list.

But what if now, you want to add or use another sorting criteria defined in Book class… Here comes the need of Comparator.
There are two ways listed here to use the Comparator class.

First method

We create a anonymous class that implements Comparator and overrides compare method.

Collections.sort(list, new Comparator() {
public int compare(Object obj1, Object obj2) {
if(obj1 == null || obj2 == null){
throw new NullPointerException("compareTo: Argument passed is null");
}
Book book1 = (Book) obj1;
Book book2 = (Book) obj2;
return book1.isbn - book2.isbn;
}
});

#### Second Method

You define a class that implements Comparator like as below.

class BookComparator implements Comparator{

public int compare(Object book1, Object book2){

int b1= ((Book)book1).isbn;
int b2= ((Book)book2).isbn;

if(b1> b2)
return 1;
else if(b1< b2)
return -1;
else
return 0;
}

}

And use this newly defined comparator class as an argument to Collections.sort.

Arrays.sort(list, new BookComparator ());

### Good reasons to use Comparator interface

• I do not have permissions to edit the Book class.
• Book class already implements Comparable interface, but I want to sort the objects using a different criteria
• I want to have more than 1 criterias to sort the objects in different orders.

### Reasons to implement Comparable interface

• I want my class to have a default sorting criteria that can be used by the users of my class
• Usually, one would like to sort the objects based on primary key

# JDBC Connection Scope

How should your application manage the life cycle of JDBC connections? Asked another way, this question really asks – what is the scope of the JDBC connection object within your application? Let’s consider a servlet that performs JDBC access. One possibility is to define the connection with servlet scope as follows.

import java.sql.*;

public class JDBCServlet extends HttpServlet {

private Connection connection;

public void init(ServletConfig c) throws ServletException {
//Open the connection here
}

public void destroy() {
//Close the connection here
}

public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException {
//Use the connection here
Statement stmt = connection.createStatement();
//do JDBC work.
}
}

Using this approach the servlet creates a JDBC connection when it is loaded and destroys it when it is unloaded. The doGet() method has immediate access to the connection since it has servlet scope. However the database connection is kept open for the entire lifetime of the servlet and that the database will have to retain an open connection for every user that is connected to your application. If your application supports a large number of concurrent users its scalability will be severely limited!

# Method Scope Connections

To avoid the long life time of the JDBC connection in the above example we can change the connection to have method scope as follows.

public class JDBCServlet extends HttpServlet {

private Connection getConnection() throws SQLException {
// create a JDBC connection
}

public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException {
try {
Connection connection = getConnection();
//..
connection.close();
}
catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
}

This approach represents a significant improvement over our first example because now the connection’s life time is reduced to the time it takes to execute doGet(). The number of connections to the back end database at any instant is reduced to the number of users who are concurrently executing doGet(). However this example will create and destroy a lot more connections than the first example and this could easily become a performance problem.

In order to retain the advantages of a method scoped connection but reduce the performance hit of creating and destroying a large number of connections we now utilize connection pooling to arrive at our finished example that illustrates the best practices of connecting pool usage.

import java.sql.*;
import javax.sql.*;

public class JDBCServlet extends HttpServlet {

private DataSource datasource;

public void init(ServletConfig config) throws ServletException {
try {
// Look up the JNDI data source only once at init time
Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
datasource = (DataSource) envCtx.lookup("jdbc/MyDataSource");
}
catch (NamingException e) {
e.printStackTrace();
}
}

private Connection getConnection() throws SQLException {
return datasource.getConnection();
}

public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException {
Connection connection=null;
try {
connection = getConnection();
....
}
catch (SQLException sqlException) {
sqlException.printStackTrace();
}
finally {
if (connection != null)
try {connection.close();} catch (SQLException e) {}
}
}
}
}

This approach uses the connection only for the minimum time the servlet requires it and also avoids creating and destroying a large number of physical database connections. The connection best practices that we have used are:

A JNDI datasource is used as a factory for connections. The JNDI datasource is instantiated only once in init() since JNDI lookup can also be slow. JNDI should be configured so that the bound datasource implements connecting pooling. Connections issued from the pooling datasource will be returned to the pool when closed.

We have moved the connection.close() into a finally block to ensure that the connection is closed even if an exception occurs during the doGet() JDBC processing. This practice is essential when using a connection pool. If a connection is not closed it will never be returned to the connection pool and become available for reuse. A finally block can also guarantee the closure of resources attached to JDBC statements and result sets when unexpected exceptions occur. Just call close() on these objects also.

For More details :
http://www.javaranch.com/journal/200601/JDBCConnectionPooling.html

## Common Mistakes in Collections

Source : http://javabeanz.wordpress.com/2007/07/13/treemap-vs-hashmap/

Classes like Integer, String, Double etc implements Comparable interface. So if we are to use an object of a custom class as the key, ensure that it’ s class implements the Comparable interface.

public class MyCustomKey implements Comparable
{
private int value;
public MyCustomKey(int value)
{
this.value = value;
}

public int compareTo (MyCustomKey key)
{
int comparison = 0;

// Note:
// Return -1 if this.value < key.value
// Return  0 if this.value = key.value
// Return  1 if this.value > key.value

return (comparison);
}
}

A common mistake that everyone does is not to override the hashcode(). If we are failing to do so, map.get(new MyCustomKey()); may not give you what you were expecting. So it is always advised to override the hashCode() if objects of that class is being used as a key.

public class MyCustomKey implements Comparable
{
private int value;
public MyCustomKey(int value)
{}
public int compareTo (MyCustomKey key)
{}

public int hashCode()
{
// Note:
// If two objects are equal then their corresponding hashCode ()
// should return the same value too.
return (this.value * 199);
}
}

When you are using your custom object as a key to a HashMap, make sure you do the following

1) implement Comparable
2) override compareTo method, and give its implementation
3) override hashCode and equals method, and give their implementation.
4) Always, make your key object as immutable, so that it is not changed after you add it to a HashMap as key.