The error is with the line:
if int(b[j]) == (len(b)-1):
That is, since you are comparing the element j of array b, if you update the array b (by the pop function) the length changes too. Meaning, there may be another number that will be popped instead of only the value N-1.
Fix this by making a variable assigned with the initial value of len(b)-1 so that it will not change throughout the loop.
An easier way is to use remove(). That is b.remove(len(b)-1). It removes the first occurrence of the value in the list. You wouldn’t even need a loop for it!
Hope it helps~!