C Program to Delete an Element in an Array
In this article, we will learn to how delete an element from an array in C. C arrays are static in size, it means that we cannot remove the element from the array memory. But we can logically delete the element by overwriting it and updating the size variable.
Delete the Given Element from an Array
To delete an element using its value from an array, first find the position of the element using a loop and then shift all the element to the right of it one position to the left. Let's take a look at an example:
#include <stdio.h>
void del(int arr[], int *n, int key) {
// Find the element
int i = 0;
while (arr[i] != key) i++;
// Shifting the right side elements one
// position towards left
for (int j = i; j < *n - 1; j++) {
arr[j] = arr[j + 1];
}
// Decrease the size
(*n)--;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;
// Delete the key from array
del(arr, &n, key);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
10 20 40 50
Explanation: In the given program, the function del() deletes an element from the array arr[] based on the provided key. It first finds the position of the key using a loop. Once found, all elements to the right of the key are shifted one position to the left to overwrite the deleted element. Finally, the size of the array is decremented by modifying the value pointed to by n.
Time Complexity: O(n) (for Searching) + O(n) (for Shifting) + O(1) (for decrementing size) = O(n)
Auxiliary Space: O(1)
Delete the Last Element from an Array
In the above method, we can get a special case where we don't need to shift any element. It's the case where the element to be deleted is present at last. But we still need to find the position of the element, which will take O(n) time. But what if we are already told that we have to delete the last element?
In this case, we can just decrease the size of the array without shifting the element leading to O(1) time for deletion. The below example demonstrates that:
#include <stdio.h>
void delLast(int arr[], int *n) {
// Decrease the size
(*n)--;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
// Delete the last element
delLast(arr, &n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
10 20 30 40
Time Complexity: O(1) (for decrementing size)
Auxiliary Space: O(1)