Delete an element from array ( Using two traversals and one traversal ) | This function removes an element x from arr [ ] and returns new size after removal . Returned size is n - 1 when element is present . Otherwise 0 is returned to indicate failure . ; If x is last element , nothing to do ; Start from rightmost element and keep moving elements one position ahead . ; If element was not found ; Else move the next element in place of x ; Driver code ; Delete x from arr [ ]
def deleteElement ( arr , n , x ) : NEW_LINE INDENT if arr [ n - 1 ] == x : NEW_LINE INDENT return n - 1 NEW_LINE DEDENT prev = arr [ n - 1 ] NEW_LINE for i in range ( n - 2 , 1 , - 1 ) : NEW_LINE INDENT if arr [ i ] != x : NEW_LINE INDENT curr = arr [ i ] NEW_LINE arr [ i ] = prev NEW_LINE prev = curr NEW_LINE DEDENT DEDENT if i < 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT arr [ i ] = prev NEW_LINE return n - 1 NEW_LINE DEDENT arr = [ 11 , 15 , 6 , 8 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE x = 6 NEW_LINE n = deleteElement ( arr , n , x ) NEW_LINE print ( " Modified ▁ array ▁ is " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT