This appeared in a HackerRank Test. Minor improvisations over brute force also gives time out error. Python solutions (or psuedo code) please!