solution to hackerrank tw problem