Modified the approach to the problem and added some unit tests