Thursday, October 02, 2014

Last Non-repeat Element

Given a stream of object, make a function to return last non repeating object.
(I was confused by definition of steam, it can simply mean a collection of object)

Solution:
use a Set or HashMap to figure out the repeating of objects, then use a Deque to access head or tail in O(1) time. Collection has convenient method to remove object: remove(o).


package LastNonRepeatCharacter;

import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import java.util.stream.Stream;
/**
* return last non-repeating object
*
* @author Andrew Ma
*
*/
public class SolutionObject {
 Deque<Object> nonRepeating = new LinkedList<Object>();
 Set<Object> metSoFar = new HashSet<Object>();
 Object getLastNonRepeatCharacter(){
  if(nonRepeating.isEmpty())return null;
  return nonRepeating.getLast();
 }
 public void reset(){
  nonRepeating.clear();
  metSoFar.clear();
 }
 public void stream(Collection<Object> inStream){
  stream(inStream.stream());
 }
 public void stream(Stream<Object> inStream){
  inStream.forEach(e->{
   if(!metSoFar.add(e)){
    nonRepeating.remove(e);//this is from collection, and might be expensive and worst at O(n) depending on implementation
   }
   else
    nonRepeating.addLast(e);
  });

 }

 public static void main(String[] args) {
  SolutionObject s = new SolutionObject();
  String[] str = new String[]{"abc","bcd","cde","def","fee"};
  String[] str2 = {"abc","bcd","cde","def","fee","fee"};
  s.stream(Arrays.asList(str));
  System.out.println("test1:"+s.getLastNonRepeatCharacter());
  s.reset();
  s.stream(Arrays.asList(str2));
  System.out.println("test2:"+s.getLastNonRepeatCharacter());
 }
}

Wednesday, October 01, 2014

A Furniture Testing OOD

My lessons learned: do not try to surprise the other people, just model the real world in a simple way. keep the objects decoupled and cohesive.

Check if a String is Balanced on Brackets

Tried the source code beautifier and love it! For the first time, I was able to easily post Java code on blogspot. :)
The new post is a solution I gave out in a phone interview. Later I found somebody has posted similar solution on the Internet.
I felt glad to see my thoughts was so right at its first reaction.
Problem: please figure out if a given string is balanced on special brackets pairs.
the bracket pairs are () and [].
"abcdeee" is balanced.
"abc(deddd)ffsd" is balanced because ) closes (
"abc(dfsdfsd]dfsdfsd" is not balanced because ( has no closing ) and ] has no openning [
":abc([sdfdfd)]sdfdfs" is not balanced because the bracket can nest in another bracket but they can not overlap the others

Solution: using stack to check if the brackets are matching.

this code can be improved by using predefined string to compare run time string. e.g. leftB.euqals(tmp) instead of tmp.equals(leftB) to avoid null pointer exception.

static boolean isBalanced(String statement) {
         Stack<Character> sHelper = new Stack<Character>();
         Character tmp;
         Character leftP = new Character('(');
         Character rightP = new Character(')');
         Character leftB = new Character('[');
         Character rightB = new Character(']');
         if (statement == null) return false;
         for (int i=0;i<statement.length();i++){
             tmp = statement.charAt(i);
             if (tmp.equals(leftB) || tmp.equals(leftP)){
                 sHelper.push(tmp);
             }else if (tmp.equals(rightB) ){
                 if (!sHelper.isEmpty() && leftB.equals(sHelper.peek()))
                     sHelper.pop();
                 else
                 return false;
                 
             }else if (tmp.equals(rightP) ){
                 if (!sHelper.isEmpty() && leftP.equals(sHelper.peek()))
                     sHelper.pop();
                 else
                 return false;
             }
         }
         return sHelper.empty();
     }