Why it works
- Everything left of write is the answer so far, and it is sorted. If nums[read] equals nums[write - 2], it equals everything between them too, so the answer already ends with two copies of it, and a third is one too many.
- The neighbour is not enough: equal neighbours only say that the number repeats, not how many copies are already kept. In 1, 1, 1 the second and the third 1 look the same next to their neighbours, yet only the third must go. nums[write - 2] counts for us.
- At most k times: keep the first k numbers and compare with nums[write - k]. With k = 1 this is problem 26, Remove Duplicates from Sorted Array.
Complexity
Time O(n): read passes the array once, and each step is one comparison and at most one copy. Memory O(1): the array is rewritten in place, with only two indices on the side.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗