Here’s my python solution in case anyone is looking up this question. Works for m >= 1 but unfortunately not for m = 0. I like it though since it looks similar to the original algo.
def fcn(arr, m):
vacant, l, n = 1, 1, len(arr)
# vacant represents the index at which to move current array element
# l is how many times the number of interest appears. l set to 1 because
# first element appears at least once.
# number of interest is number immediately before vacant
for i in range(1, n):
if arr[i] == arr[vacant - 1] and l < min(2, m):
arr[vacant] = arr[i]
vacant, l = vacant + 1, l + 1
# ex) [2, 2, 3 ...] where vacant = 1
# 2 is the number of interest and appears once (so far). Because l < min(2, m),
# we increment l by 1, and increment the vacant position by 1 because need
# the number at arr[vacant - 1] to appear at least l times.
elif not arr[i] == arr[vacant - 1]:
arr[vacant] = arr[i]
l, vacant = 1, vacant + 1
# when we hit this conditional, it means that we're operating on a new
# number of interest, thus we reset l to 1 because the element at arr[i]
# appears once (so far), and subsequently we move it back to vacant.
# outside of the conditional, we don't want to increment vacant if we run into
# the number of interest more than min(2, m) times. ex) [2, 2, 2, 2, 2, ....]
# we only want the number of interest - 2 - to appear min(m, 2) times, so the vacant
# position is the one right after 2 appears min(m, 2) times.
return arr[:vacant][:]