I made a mistake it actually should be O(N) for the second solution because it depends on the total number of words in the document. That is different from M which is the number of distinct words in the document. So first solution is O(MlogM) and second solution is O(N). I found this problem on Pramp's website.