Delete array element in given index range [L – R]
Last Updated :
01 Mar, 2023
Improve
Given an array A[] and the size of an array is N. The task is to delete elements of array A[] that are in the given range L to R both are exclusive.
Examples:
Input : N = 12 A[] = { 3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3} L = 2 R = 7 Output : 3 5 3 6 3 11 12 3 since A[2] = 3 but this is exclude A[7] = 6 this also exclude Input : N = 10 A[] ={ 5, 8, 11, 15, 26, 14, 19, 17, 10, 14 } L = 4 R = 6 Output :5 8 11 15 26 19 17 10 14
A naive approach is to delete elements in the range L to R with extra space.
Below is the implementation of the above approach:
- C
- C++
- Java
- Python3
- C#
- PHP
- Javascript
C
// C++ code to delete element // in given range #include <stdio.h> #include <stdlib.h> // Delete L to R element void deleteElement( int A[], int L, int R, int N, int *size, int *B) { int index=0; for ( int i = 0; i < N; i++) if (i <= L || i >= R) B[index++]=A[i]; *size=index; } // main Driver int main() { int A[] = { 3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3 }; int L = 2, R = 7; int n = sizeof (A) / sizeof (A[0]); int B[n- abs (L-R)]; int size=0; deleteElement(A, L, R, n,&size,B); for ( int i=0;i<size;i++) printf ( "%d " ,B[i]); return 0; } |
C++
Java
Python3
C#
PHP
Javascript
Output
3 5 3 6 3 11 12 3
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space : O(n)
An efficient solution without using extra space.
Below is the implementation of the above approach:
- C
- C++
- Java
- Python 3
- C#
- PHP
- Javascript
C
// C code to delete element // in given range #include <stdio.h> // Delete L to R elements int deleteElement( int A[], int L, int R, int N) { int i, j = 0; for (i = 0; i < N; i++) { if (i <= L || i >= R) { A[j] = A[i]; j++; } } // Return size of Array // after delete element return j; } // Driver Code int main() { int A[] = { 5, 8, 11, 15, 26, 14, 19, 17, 10, 14 }; int L = 2, R = 7; int n = sizeof (A) / sizeof (A[0]); int res_size = deleteElement(A, L, R, n); for ( int i = 0; i < res_size; i++) printf ( "%d " , A[i]); return 0; } |
C++
Java
Python 3
C#
PHP
Javascript
Output
5 8 11 17 10 14
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space : O(1)