Problem Link - Deletion from an array
Problem Statement:
Deleting elements from a 1D
array involves removing an element from a specific position within the array and then shifting the remaining elements to fill the gap.
Here’s a step-by-step process for deleting elements from a 1D
array:
-
Determine the Position: Decide which element you want to delete from the array. You need to know the index (position) of the element you want to remove.
-
Shift Elements: Starting from the position of the element to be deleted, move each element one position to the left until you reach the end of the array. This fills the gap left by the deleted element.
-
Update Array Size: If your array is dynamically allocated or you’re using a mechanism that tracks the size, decrease the size of the array to reflect the new number of elements.
Approach:
To remove an element from a specific position in an array, start by identifying the index of the element to be deleted. Then, shift all subsequent elements one position to the left, overwriting the deleted element and effectively reducing the size of the array by one:
-
Shift Elements: Starting from the index of the deleted element, shift each subsequent element one position to the left, effectively overwriting the deleted element.
-
Update Size: Decrease the size of the array by one to reflect the removal.
-
Print the Updated Array: Display the elements of the modified array.
Time Complexity:
- O(n): Where n is the size of the array (for shifting elements).
Space Complexity:
- O(1): No additional space used; the operation is done in place.