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

2

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

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 C++ and Java implementation of this simple approach.

C/C++

// 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;
}

Java

// 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*/


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++

// 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;
}

Java

// 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*/


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.

GATE CS Corner    Company Wise Coding Practice

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

Recommended Posts:



2 Average Difficulty : 2/5.0
Based on 22 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.