O(nlogk) pip implementation