O(kn) version
log n solution