http://www.hackerearth.com/problem/algorithm/foo-and-exams-4/ solved