implementing valiant's algo