Revert "remove some O(n^2) algorithms in the front end" [fix #2270].

This reverts commit c503312f1c4c2496163c41a233caa8076ba35425.