refactored linear time mmd