O(1) space + O(n) time - Java solution


  • 0
    W
    public int removeElement(int[] A, int elem) {
        int length = A.length;
        
        if(0==length)
            return 0;
    
           //counter is to keep track of new length!
    
        int counter = 1;
        int i = 0;
    
           //To handle if the 1st ele was supposed to be removed -- Start with a negative index.
    
        if(A[i]==elem){
            i = -1;
            counter -= 1;
        }
        for(int j = 1; j < length; j++){
    
               //Continuously replace ele by itself/new ele when the toBeDeleted ele is not found.
    
            if(A[j] != elem){
                A[++i] = A[j];
                counter++;
            }
        }
        
        return counter;
    } 
    

    Feel free to ask me any questions should you not understand the code above!

    OR

    Suggestions as to how I could improve my solution!

    Cheers.


  • 0
    H
      public int removeElement(int[] A, int elem) {
            int counter = 0;
            for(int i = 0, j = 0; j < A.length; j++) {
                if(A[j] != elem) {
                    A[i++] = A[j];
                    counter++;
                }
            }
            return counter;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.