rewrite with KMP