Search This Blog

Thursday, June 23, 2011

Reverse a singly linked list

I was asked this question during an interview today.  I didn't do well though.  I guess because it was an interview, I had some pressure and could think fast and clearly.  In fact, this question is pretty easy with the recursive.  When I got home, it didn't take me too long to figure out the correct answer.  Here is the code in Java.

class Node {
    Node next;
}

class Util {
    public static void reverseNode(Node node) {
        reverseNode(node, null);
    }
   
    private static void reverseNode(Node node, Node previous) {
        if (node != null) {
            reverseNode(node.next, node);
            node.next = previous;
        }
    }
}

Update:

The recursive solution is easy to understand and implement.  However, you may get a StackOverflow exception if the list is big.  Here is the non-recursive solution:

class Util {
    public static void reverseNode(Node node) {
        Node previous = null;
        while (node != null) {
            Node next = node.next;
            node.next = previous;
            previous = node;
            node = next;
        }
    }
}

Tuesday, June 21, 2011

Swap 2 integers without using a temp variable

There are 2 ways to do it. 
  1. use sum of the 2 variables:
 void swap(int a, int b) {
       a = a + b;
       b = a - b;
       a = a - b
    }

     2. use bitwise operation (xor)
void swap(int a, int b) {
      a = a ^ b;
      b = a ^ b;
      a = a ^ b;
    }

Create Singleton in Java

A singleton is simply a class that is instantiated exactly once.  There are two approaches to create a singleton class.
  1. Early initialization,
  2. Lazy initialization.
 There are several ways to create singleton in each approach.

For early initialization:
  1. Singleton with public final field
public class Singleton {
      public static final Singleton INSTANCE = new Singleton();

      private Singleton() {
         //do something
      }

      public void someMethod() {
         // do something
      }
    }

     2. Singleton with static factory
public class Singleton {
     private static final Singleton INSTANCE = new Singleton();
     
     private Singleton() {
         //do something
     }

     public static Singleton getInstance(){
       return INSTANCE
     }

     public void someMethod() {
         // do something
     }   
   }
  
      3. Singleton with enum
public enum Singleton {
      INSTANCE;
            
      private Singleton() {
         //do something
      }

      public void someMethod() {

         // do something
      }    
    }


For lazy initialization:

  However unless you absolutely need it, don't use lazy initialization.

     1. Lazy initialization holder class idiom for static fields (a class will not be initialized until it is used)

public class LazySingleton {
     private static class SingletonHolder {
       static final LazySingleton INSTANCE = new LazySingleton();
     }
     
     private LazySingleton() {
         //do something
     }

     public static LazySingleton getInstance(){
       return SingletonHolder.INSTANCE;
     }

     public void someMethod() {
         // do something
     }
    }

 2. Double-check idiom for lazy initialization

   class LazySingleton {
     private static volatile LazySingleton instance;
     private LazySingleton(){

        //do something
     }


     public static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (
LazySingleton.class) {
                if (instance == null) {
                    INSTANCE = new LazySingleton();
                }
            }
        }
        return instance;

     }
   }

Monday, June 20, 2011

Reverse the string word by word, in place

The idea is reverse the string character by character first, then reverse the word character by character.  For example, we have string "abc defg hijk".  The first step is to reverse the string character by character:

"abc defg hijk" ==> "kjih gfed cba"

Then reverse the word in the output string character by character:

"kjih gfed cba" ==> "hijk defg abc"

The run time is O(n) with constant extra space.  Here is the code in java:

    public static void resverseString(char[] input) {
        reverseString(input, 0, input.length - 1);
        int start = 0;
        int end = 0;
        for (char temp : input) {
            if (temp == ' ') {
                reverseString(input, start, end - 1);
                start = end + 1;
            }
            end++;
        }
        reverseString(input, start, end - 1);
    }
   
    private static void reverseString(char[] input, int start, int end) {
        while (start < end) {
            swap(input, start, end);
            start++;
            end--;
        }
    }
   
    private static void swap (char[] input, int i, int j) {
        char temp = input[i];
        input[i] = input[j];
        input[j] = temp;
    }

Wednesday, June 15, 2011

Weak Reference in Java

Today, during a phone interview, I was asked a question about WeakReference in Java.  I only knew that the weak referenced object can be garbage collected by JVM, and nothing more.  I did a little research, and realized that there are 4 types of references in Java:
  1. Strong Reference
  2. Soft Reference
  3. Weak Reference
  4. Phantom Reference
They are in the order from strong to weak references.  3 classes, SoftReference, WeakReference, and PhantomReference are for the last 3 references.  For strong reference, just use new operator. Below is a great blog talking about all 4 references:

Understanding Weak References

Tuesday, June 14, 2011

Print a sequence of Fibonacci number

The trick is that you should use BigInteger instead of long.  Otherwise, you will get overflow pretty soon.  Here is the code:

import java.math.BigInteger;

public class Fibonacci {
    /**
     * print out a list of Fibonacci sequence to n places.
     * if n = 0, no number will be printed out.  if n = 1, print the first Fibonacci number.
     *
     * @param n the number of Fibonacci to be printed out
     */
    public static void print(int n) {
        BigInteger f0 = BigInteger.ZERO;
        BigInteger f1 = BigInteger.ONE;
        for (int i = 0; i < n; i++) {
           
            System.out.print(f0);
            if (i != n - 1) {
                System.out.print(", ");
            }
            BigInteger temp = f1;
            f1 = f1.add(f0);
            f0 = temp;
        }
    }
}

Update: Another thing to consider is that don't use recursive method to compute Fibonacci number because it is too expensive.  The run time is 2^n to recursively compute Fibancci number.

Monday, June 13, 2011

Print a singly linked list reversely

For a singly linked list, you can only access the list element from the head.  At the first glance, it seems difficulty printing the element reversely (the tail first).  However if you know recursive, the problem becomes quite easy. Here is how to solve this problem in Java:

public class ListUtil {
    public static <T> void  reversePrint(List<T> list) {
        if (list == null || list.isEmpty()) {
            System.out.println("empty list");
        } else {
            Iterator<T> iter = list.iterator();
            reversePrint(iter);
        }
    }
   
    private static <T> void reversePrint(Iterator<T> iter) {
        if (iter.hasNext()) {
            T data = iter.next();
            reversePrint(iter);
            System.out.println(data);
        }
    }
}