Home > Mobile >  Remove Duplicates From Sorted Array Logic Throwing Exception For Correct Answer in C#
Remove Duplicates From Sorted Array Logic Throwing Exception For Correct Answer in C#

Time:11-04

I answered a LeetCode question by the name of 'Remove Duplicates from Sorted Array' in two similar languages to prepare for different interviews. My Java solution was marked as correct, but the C# solution throws a Runtime Error with the message Unhandled exception. System.ArgumentException: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.

My correct solution in Java is as follows:

public int removeDuplicates(int[] nums) {
    
        int pointer1 = 0;
        
        for (int pointer2 = 1; pointer2 < nums.length; pointer2  ) {
            if (nums[pointer1] != nums[pointer2]) {
                pointer1  ;
                nums[pointer1] = nums[pointer2];
            }
        }
        
        return pointer1   1;
    }

My incorrect solution in C# is as follows:

public int RemoveDuplicates(int[] nums)
        {
            int pointer1 = 0;

            for (int pointer2 = 1; pointer2 < nums.Length; pointer2  )
            {
                if (nums[pointer1] != nums[pointer2])
                {
                    pointer1  ;
                    nums[pointer1] = nums[pointer2];
                }
            }

            return pointer1   1;
        }

The requirement was to do this in-place, so I avoided using extra memory. I'm having trouble understanding why length was out of bounds for the array when I specified the length within the loop's scope. Also this error is only thrown when attempting the C# solution. I'm working to get better at C# and would like to know what the issue with my implementation is. Thank you for any and all feedback.

CodePudding user response:

It's probably not your code that's throwing, since the only OutOfRange exception you would get from it would be "Index out of bounds", not "Offset and length out of bounds". Whatever calls your code throws.

It probably tries to run your method on an empty array or a null, try returning 0 or -1 when nums.Length == 0 or nums == null.

(From comments: yep, it expected 0 when an empty array was passed as argument. The check needed was:

if (nums.Length == 0)
    return 0;

).

  • Related