that is the best but there is one catch here. dim could be 2**32 and your hashed_doc vector too large to fit in memory. Better use DynamicArray for that and append all the indices. Then sort this array and when compute how often each index appears adding them to the .entry.