KM algorithm