← Home

540. Single Element in a Sorted Array

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
binary searchC++Markdown
540

This is one of those problems where the clean idea matters more than the amount of code. For 540. Single Element in a Sorted Array, the solution in this repository is mainly a binary search solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: binary search, two pointers, sliding window, bit manipulation.

The notes already sitting in the source point us in the right direction:

  • time: O(N), space: O(1)

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are singleNonDuplicate, afterSingle.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 16 ms, faster than 29.23% of C++ online submissions for Single Element in a Sorted Array.
02//Memory Usage: 11.2 MB, less than 7.14% of C++ online submissions for Single Element in a Sorted Array.
03//time: O(N), space: O(1)
04class Solution {
05public:
06    int singleNonDuplicate(vector<int>& nums) {
07        int ans = 0;
08        for(int num : nums){
09            ans ^= num;
10        }
11        return ans;
12    }
13};
14
15//binary saerch
16//Runtime: 12 ms, faster than 47.40% of C++ online submissions for Single Element in a Sorted Array.
17//Memory Usage: 11.1 MB, less than 7.14% of C++ online submissions for Single Element in a Sorted Array.
18class Solution {
19public:
20    bool afterSingle(vector<int>& nums, int mid){
21        int n = nums.size();
22        
23        // if(mid % 2 == 0){
24        if(!(mid&1)){ //speed up from 16ms to 12ms
25            //nums[mid] should equal to nums[mid+1]
26            //if mid is even, mid must < n(n is always odd)
27            if(mid+1 < n && nums[mid] == nums[mid+1]){
28                //single element is on its right
29                return false;
30            }else{
31                //single element is on its left
32                return true;
33            }
34        }else{
35            //nums[mid] should equal to nums[mid-1]
36            //if mid is odd, mid must > 0
37            if(/*mid > 0 && */nums[mid] == nums[mid-1]){
38                //single element is on its right
39                return false;
40            }else{
41                //single element is on its left
42                return true;
43            }
44        }
45    };
46    
47    int singleNonDuplicate(vector<int>& nums) {
48        int n = nums.size();
49        int left = 0, right = n-1;
50        int mid;
51        
52        while(left <= right){
53            mid = left + (right - left)/2;
54            // cout << left << ", " << mid << ", " << right << endl;
55            
56            if(afterSingle(nums, mid)){
57                right = mid-1;
58            }else{
59                left = mid+1;
60            }
61        }
62        
63        return nums[left];
64    }
65};
66
67//https://leetcode.com/problems/single-element-in-a-sorted-array/discuss/100754/Java-Binary-Search-short-(7l)-O(log(n))-w-explanations
68//Runtime: 16 ms, faster than 29.23% of C++ online submissions for Single Element in a Sorted Array.
69//Memory Usage: 11.3 MB, less than 7.14% of C++ online submissions for Single Element in a Sorted Array.
70class Solution {
71public:
72    int singleNonDuplicate(vector<int>& nums) {
73        int left = 0, right = nums.size()-1;
74        int mid;
75        
76        /*
77        althrough the boundary is inclusive in both ends: [left, right],
78        we don't use left <= right,
79        because we only search when the search range >= 2
80        (we examine two elements at a time)
81        */
82        while(left < right){
83            mid = left + (right - left)/2;
84            //if mid is odd
85            if(mid&1) mid--;
86            //here mid is always even!!
87            if(nums[mid] != nums[mid+1]){
88                right = mid-1;
89            }else{
90                //we have examined mid and mid+1
91                //left is always even!!
92                left = mid+2;
93            }
94        }
95        
96        return nums[left];
97    }
98};

Cost

Complexity

Time
O(N), space: O(1)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.