algorithm to remove element from an array

This can be achieved in many ways, some of them are discussed here
– standard way when existing order is important: traverse through the elements, once element_to_be_deleted is found, shift remaining elements one position towards left. The complexity of this algorithm is O(n)
– when order of array is not important: take two pointers; one at the beginning of array and another at the end of the array. Increment the starting pointer till the element_to_be_deleted is found and decrement the ending pointer till element is not equals to element_to_be_deleted and then swap elements at start_pointer and end_pointer. The complexity of this algorithm is O(n)
– brute force algorithm. The complexity of this algorithm is O(n*n)

standard way when existing order is important @ O(n)

	public int removeNumber(int[] a, int n) {

		if (a == null || a.length == 0) 
			return -1;
		int i = 0;
		for (int j=0; j<a.length; j++)
			if (a[j] != n) 
				a[i++] = a[j];
		System.out.println("New size of the array is "+i);
		return i; // The new dimension of the array

when order of array is not important @ O(n)

	public void removeElementO_n(int[] a, int element) {
		int startPtr = 0; 
		int endPtr = a.length-1;
		while(startPtr < endPtr) {
			while(endPtr > 0 && a[endPtr] == element) {
			while(startPtr < a.length && a[startPtr] != element) {
			if(startPtr < endPtr) {
				a[startPtr] = a[endPtr];
				a[endPtr] = -1;

brute force algorithm @ O(n*n)

public void removeElementO_n2(int[] a, int element) {
		int ct=0;
		int ln = a.length;
		for (int i = 0; i < a.length; i++) {
			if(a[i] == element) {
				for (int j = i; j < a.length; j++) {
					if((j+1)<a.length) {
						a[j] = a[j+1];
				a[ln-ct] = -1;

One Response to algorithm to remove element from an array

  1. Sainik Kumar Singhal says:

    Your first method will actually remove the last element from array.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


Mostly technology with occasional sprinkling of other random thoughts


Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates


A topnotch site


Just another site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: