1

I am doing leetcode 540. Single Element in a Sorted Array using c++. The problem is: You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once.

Here is a example:

Input: [1,1,2,3,3,4,4,8,8]
Output: 2

I run into runtime error again:

Runtime Error Message:
AddressSanitizer: heap-buffer-overflow on address 0x602000000034 at pc 0x0000004056da bp 0x7ffcd2cff910 sp 0x7ffcd2cff908

Here is my code and it's super easy to understand.

class Solution {
public:
    int singleNonDuplicate(vector<int>& nums) {
        int n = nums.size();
        int i = 1;
        int output;
        if(nums[0] != nums[1])
            return nums[0];
        if(nums[n-1] != nums[n-2])
            return nums[n-1];
        for(i = 1; i < n-1; i++)
            {
                if(nums[i]!=nums[i-1] && nums[i]!=nums[i+1])
                {
                    output = nums[i];
                    break;
                }
            }
        return output;
    }
};

I really hope someone can help me. I met this problem several times and I have no clue what's going on.

2 Answers 2

2

In this part :

if(nums[0] != nums[1])
    return nums[0];
if(nums[n-1] != nums[n-2])
    return nums[n-1];

What if the size of nums is 0 or 1? I think you should add some sanity-check to your code, like checking for the input vector size to handle corner cases of 0 or 1 elements.

I added this condition and it is accepted now.

if(n == 1)
   return nums[0];
Sign up to request clarification or add additional context in comments.

1 Comment

It is worth mentioning that all those if aren't required. The sole loop should suffice.
0

If you start iteration from 0, not from 1 it could be significantly simplified:

int singleNonDuplicate(vector<int>& nums) 
{
   for( size_t i = 0; i < nums.size(); i += 2 )
       if( i + 1 == nums.size() || nums[i] != nums[i+1] ) 
           return nums[i];
   // if we reach here then input is wrong
   throw std::runtime_error( "wrong input" );
}

and you do not need any preconditions.

Note: on the site solution required to be O(log n), so though this loop will logically work you need more complex solution using binary search, as this solution using loop is O(n).

2 Comments

Thanks! This also works. what does "throw" mean here? I searched online, but I don't understand the specific function of it.
throw raises exception in C++. You may return error code or do something else, but cleanest way is to raise

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.