I solved this problem, but I'd like someone's help on an issue I came across while solving the problem.
Initially, I took input using java BufferedReader and submitted the solution. All except 2 test-cases passed. The 2 which failed, showed RE (NZEC).
I changed the input from BufferedReader to Scanner and all test-case passed.
Buffered-Reader Code = http://ideone.com/rBB7q5
Scanner Code = http://ideone.com/yiqfzn
I'd appreciate if someone can point out what I was doing wrong with the BufferedReader. Thanks in advance.