a more elegant version of KMP