modify build_ngram algorithm