Delete an element from array (Using two traversals and one traversal)

Given an array and a number ‘x’, write a function to delete ‘x’ from the given array.
Example:

Input:  arr[] = {3, 1, 2, 5, 90}, x = 2
Output: arr[] = {3, 1, 5, 90} 

A simple solution is to first search ‘x’ in array, then elements that are on right side of x to one position back. The following are the implementation of this simple approach.

C/C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to remove a given element from an array
#include<iostream>
using namespace std;
  
// This function removes an element x from arr[] and
// returns new size after removal (size is reduced only
// when x is present in arr[]
int deleteElement(int arr[], int n, int x)
{
   // Search x in array
   int i;
   for (i=0; i<n; i++)
      if (arr[i] == x)
         break;
  
   // If x found in array
   if (i < n)
   {
     // reduce size of array and move all
     // elements on space ahead
     n = n - 1;
     for (int j=i; j<n; j++)
        arr[j] = arr[j+1];
   }
  
   return n;
}
  
/* Driver program to test above function */
int main()
{
    int arr[] = {11, 15, 6, 8, 9, 10};
    int n = sizeof(arr)/sizeof(arr[0]);
    int x = 6;
  
    // Delete x from arr[]
    n = deleteElement(arr, n, x);
  
    cout << "Modified array is \n";
    for (int i=0; i<n; i++)
       cout << arr[i] << " ";
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to remove a given element from an array
import java.io.*;
  
class Deletion {
      
    // This function removes an element x from arr[] and
    // returns new size after removal (size is reduced only
    // when x is present in arr[]
    static int deleteElement(int arr[], int n, int x)
    {
        // Search x in array
        int i;
        for (i=0; i<n; i++)
            if (arr[i] == x)
                break;
   
        // If x found in array
        if (i < n)
        {
            // reduce size of array and move all
            // elements on space ahead
            n = n - 1;
            for (int j=i; j<n; j++)
                arr[j] = arr[j+1];
        }
   
        return n;
    }
      
    // Driver program to test above function
    public static void main(String[] args)
    {
        int arr[] = {11, 15, 6, 8, 9, 10};
        int n = arr.length;
        int x = 6;
   
        // Delete x from arr[]
        n = deleteElement(arr, n, x);
   
        System.out.println("Modified array is");
        for (int i = 0; i < n; i++)
            System.out.print(arr[i]+" ");
          
    }
}
/*This code is contributed by Devesh Agrawal*/

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to remove a given 
# element from an array
  
# This function removes an element x 
# from arr[] and returns new size after 
# removal (size is reduced only when x 
# is present in arr[]
def deleteElement(arr, n, x):
      
    # Search x in array
    for i in range(n):
        if (arr[i] == x):
            break
  
    # If x found in array
    if (i < n):
          
        # reduce size of array and move 
        # all elements on space ahead
        n = n - 1;
        for j in range(i, n, 1):
            arr[j] = arr[j + 1]
  
    return n
  
# Driver Code
if __name__ == '__main__':
    arr = [11, 15, 6, 8, 9, 10]
    n = len(arr)
    x = 6
  
    # Delete x from arr[]
    n = deleteElement(arr, n, x)
  
    print("Modified array is")
    for i in range(n):
        print(arr[i], end = " ")
          
# This code is contributed by
# Shashank_Sharma

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to remove a given element from
// an array
using System;
  
class GFG {
      
    // This function removes an element x
    // from arr[] and returns new size 
    // after removal (size is reduced only
    // when x is present in arr[]
    static int deleteElement(int []arr,
                              int n, int x)
    {
          
        // Search x in array
        int i;
        for (i = 0; i < n; i++)
            if (arr[i] == x)
                break;
  
        // If x found in array
        if (i < n)
        {
              
            // reduce size of array and
            // move all elements on 
            // space ahead
            n = n - 1;
            for (int j = i; j < n; j++)
                arr[j] = arr[j+1];
        }
  
        return n;
    }
      
    // Driver program to test above function
    public static void Main()
    {
        int []arr = {11, 15, 6, 8, 9, 10};
        int n = arr.Length;
        int x = 6;
  
        // Delete x from arr[]
        n = deleteElement(arr, n, x);
  
        Console.WriteLine("Modified array is");
        for (int i = 0; i < n; i++)
            Console.Write(arr[i]+" ");
          
    }
}
  
// This code is contributed by nitin mittal.

chevron_right


Output:



Modified array is
11 15 8 9 10

The above method requires two traversals of array, one for searching and other for moving elements.

Can we delete the element using one traversal?
This is possible under the assumption that the element is always present in array. The idea is to start from right most element and keep moving elements while searching for ‘x’. Below are C++ and Java implementations of this approach. Note that this approach may give unexpected result when ‘x’ is not present in array.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to remove a given element from an array
#include<iostream>
using namespace std;
  
// 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.
int deleteElement(int arr[], int n, int x)
{
   // If x is last element, nothing to do
   if (arr[n-1] == x)
       return (n-1);
  
   // Start from rightmost element and keep moving
   // elements one position ahead.
   int prev = arr[n-1], i;
   for (i=n-2; i>=0 && arr[i]!=x; i--)
   {
       int curr = arr[i];
       arr[i] = prev;
       prev = curr;
   }
  
   // If element was not found
   if (i < 0)
     return 0;
  
   // Else move the next element in place of x
   arr[i] = prev;
  
   return (n-1);
}
  
/* Driver program to test above function */
int main()
{
    int arr[] = {11, 15, 6, 8, 9, 10};
    int n = sizeof(arr)/sizeof(arr[0]);
    int x = 6;
  
    // Delete x from arr[]
    n = deleteElement(arr, n, x);
  
    cout << "Modified array is \n";
    for (int i=0; i<n; i++)
       cout << arr[i] << " ";
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to remove a given element from an array
import java.io.*;
  
class Deletion
{
    // 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.
    static int deleteElement(int arr[], int n, int x)
    {
        // If x is last element, nothing to do
        if (arr[n-1] == x)
            return (n-1);
  
        // Start from rightmost element and keep moving
        // elements one position ahead.
        int prev = arr[n-1], i;
        for (i=n-2; i>=0 && arr[i]!=x; i--)
        {
            int curr = arr[i];
            arr[i] = prev;
            prev = curr;
        }
  
        // If element was not found
        if (i < 0)
            return 0;
  
        // Else move the next element in place of x
        arr[i] = prev;
  
        return (n-1);
    }
  
    // Driver program to test above function
    public static void main(String[] args)
    {
        int arr[] = {11, 15, 6, 8, 9, 10};
        int n = arr.length;
        int x = 6;
  
        // Delete x from arr[]
        n = deleteElement(arr, n, x);
  
        System.out.println("Modified array is");
        for (int i = 0; i < n; i++)
            System.out.print(arr[i]+" ");
  
    }
}
/*This code is contributed by Devesh Agrawal*/

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# python program to remove a given element from an array 
  
  
# 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. 
def deleteElement(arr,n,x):
  
    # If x is last element, nothing to do 
    if arr[n-1]==x:
        return n-1
  
    # Start from rightmost element and keep moving 
   # elements one position ahead. 
  
    prev = arr[n-1]
    for i in range(n-2,1,-1):
        if arr[i]!=x:
            curr = arr[i]
            arr[i] = prev
            prev = curr
  
    # If element was not found 
    if i<0:
        return 0
  
    # Else move the next element in place of x 
    arr[i] = prev
    return n-1
  
  
# Driver code
arr = [11,15,6,8,9,10]
n = len(arr)
x = 6
n = deleteElement(arr,n,x)
print("Modified array is")
for i in range(n):
    print(arr[i],end=" ")
  
# This code is contributed by Shrikant13

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to remove a given
// element from an array
using System;
class GFG {
      
    // 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.
    static int deleteElement(int []arr, 
                             int n, 
                             int x)
    {
          
        // If x is last element,
        // nothing to do
        if (arr[n - 1] == x)
            return (n - 1);
  
        // Start from rightmost 
        // element and keep moving
        // elements one position ahead.
        int prev = arr[n - 1], i;
        for (i = n - 2; i >= 0 &&
                arr[i] != x; i--)
        {
            int curr = arr[i];
            arr[i] = prev;
            prev = curr;
        }
  
        // If element was 
        // not found
        if (i < 0)
            return 0;
  
        // Else move the next 
        // element in place of x
        arr[i] = prev;
  
        return (n - 1);
    }
  
    // Driver Code 
    public static void Main()
    {
        int []arr = {11, 15, 6, 8, 9, 10};
        int n = arr.Length;
        int x = 6;
  
        // Delete x from arr[]
        n = deleteElement(arr, n, x);
  
        Console.WriteLine("Modified array is");
        for(int i = 0; i < n; i++)
            Console.Write(arr[i]+" ");
  
    }
}
  
// This code is contributed by anuj_67.

chevron_right



Output:

Modified array is
11 15 8 9 10

Deleting an element from an array takes O(n) time even if we are given index of the element to be deleted. The time complexity remains O(n) for sorted arrays as well.
In linked list, if we know the pointer to the previous node of the node to be deleted, we can do deletion in O(1) time.

This article is contributed by Himanshu. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.