# What about my O(n) solution

• Here is the code in C++.

``````class Solution {
public:
int removeElement(int A[], int n, int elem) {
if (n == 0) return 0;

int newLength = n;
for (int index = 0; index != newLength; ++index)
{
if (A[index] == elem)
{
// Use the last element to cover the current element
// And decrease the newLength by 1
A[index] = A[newLength-1];
--newLength;
// Decrease the index so that the new current element
// can be checked in next loop
--index;
}
}
return newLength;
}
};
``````

Any better ?

• Did you verify that this works? What if the last element you use to cover the current element IS the element? You don't seem to check for that.

• If the last element you use to cover the current element IS the element, it means that the current element is the last one. And "--newLength;" will make it work.

• Don't really need to do these + and - on index

``````     int backP = n - 1;
int index = 0;

while(index <= backP)
{
if (A[index] == elem)
{
A[index] = A[backP];
--backP;
} else
{
++index;
}
}
return index;
``````