Fixed input problem.
Created test cases for program.
Optimized the order of variables, and use a map for duplicate lookups.