better algoritham, thanks @Darshan