Skip to content

Instantly share code, notes, and snippets.

@jatinsharrma
Last active April 23, 2020 07:34
Show Gist options
  • Save jatinsharrma/b1c1b1ab14fa7a94493323b15cec738d to your computer and use it in GitHub Desktop.
Save jatinsharrma/b1c1b1ab14fa7a94493323b15cec738d to your computer and use it in GitHub Desktop.
Move all occurrences of given element to last
#--------------------------------------------------------------
#--------Move all occurrences of given element to last----------
#--------------------------------------------------------------
'''
Question : Move all occurrences of given element to the last and we don't care about other
element's order
We could sort the array and then move the element to the last but it will take O(nlogn) time
That is not the best solution to do this
Logic :
suppose we are given [1,2,3,4,2,5,6,2] and element to move is 2
we take 2 pointers
i = 0 // first index
j = len(given) - 1 // last index
[ 1 , 2 , 3 , 4 , 2 , 5 , 6 , 2 ]
i j
> Element at index j is same as the given element. So element at j is at desired place
move j one before
[ 1 , 2 , 3 , 4 , 2 , 5 , 6 , 2 ]
i j
> Element at j is not same to given element. So we won't move one back.
Now we see element at i, it is also not equal to given element. We will shift i one ahead now
[ 1 , 2 , 3 , 4 , 2 , 5 , 6 , 2 ]
i j
> Element at j is not same to given element. So we won't move one back.
Now we see element at i, it is equal to given element.
So we will swap element at j and i .After this we will shift i one ahead now and j one back
[ 1 , 6 , 3 , 4 , 2 , 5 , 2 , 2 ]
i j
> Same will continue
[ 1 , 6 , 3 , 4 , 2 , 5 , 2 , 2 ]
i j
[ 1 , 6 , 3 , 4 , 2 , 5 , 2 , 2 ]
i j
[ 1 , 6 , 3 , 4 , 5 , 2 , 2 , 2 ]
j i
Both i become less than i, that means we have scanned whole array. So we can stop here
result [ 1 , 6 , 3 , 4 , 5 , 2 , 2 , 2 ]
'''
def moveToEnd(array,value):
i = 0
j = len(array) - 1
while i <= j:
if array[j] == value:
j -= 1
continue
if array[i] == value:
array[i],array[j] = array[j],array[i]
j -= 1
i += 1
return array
print(moveToEnd([1,6,3,4,2,5,2,2],3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment