What should be the answer for input "[]"?


  • 0
    C

    I returned 0 for this case, however, the judgement needs "[]", while there must be an integer to be returned, I am confused about what exactly should I return for this problem? Thanks for any hints. Here is my code, and could any one point out where I am wrong?

    int removeDuplicates(int arr[], int n) {
        if (arr == NULL) return 0;
    
        int ind = 1;
        int cur = 1;
    
        while (cur < n) {
    	    if (arr[cur] != arr[cur-1]) {
    		    arr[ind++] = arr[cur];
    	    }
    	    ++cur;
        }
    
        return ind;
    }
    

    The above code always gets a hint from the judge of returning "[]" which is a NULL pointer rather than an integer demanded by the function return type, finally I find out where I am wrong, the input pointer could be non-NULL with n equals to 0. So the special case should be:

    if (n == 0) {arr = NULL; return 0;}
    

    As a conclusion, I strongly suggest input cases to be clarified in this problem, so we would not be confused by the hint from the judge!!


  • 0

    That means your code is not correct. Your code must have returned the value 1 for an empty array input. ([]).

    Please see the other question, it might help you in understanding what value you should return.


  • 0
    C

    Thank you, but why should the return length of NULL input be 1? I returned 0 for NULL input in my code as an extremely case.


  • 0
    C

    sorry, I read that thread but still don't get it, I added my code above, please help me with it


  • 0
    C

    Finally, I get where I am wrong, the key point is about the meaning of the input. In my code, I assume that when the input is an empty array, then arr must be NULL, however it is not the case. We could only determine an array is empty or not from the length of that array, namely n in this case. So the extreme case should be altered into:

    if (n == 0) {arr = NULL, return 0;}
    

    Thank you!!


  • 0
    P
    This post is deleted!

  • 0
    S

    Only code here is not allowed. Please read the FAQ.


  • 0
    V

    if(arr==null || arr.length<=0){return 0;}
    This would be right.


Log in to reply
 

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