Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 540: Single Element in a Sorted Array

ArrayBinary Search

LeetCode 540 Solution Explanation

Explanation

To find the single element in a sorted array with elements appearing twice except for one element, we can utilize the property of the array being sorted. We can perform a binary search to efficiently find the single element.

  1. We start by initializing two pointers, low and high, to the beginning and end of the array respectively.
  2. We calculate the middle index mid.
  3. We check if the middle element is the single element or if it is on the left or right side.
  4. If the middle element is not the single element, we check if the single element lies on the left or right side based on the following conditions:
    • If mid is even and mid + 1 element is equal to mid element, then the single element is on the right side, so we move low to mid + 2.
    • If mid is odd and mid - 1 element is equal to mid element, then the single element is on the right side, so we move low to mid + 1.
    • Otherwise, the single element is on the left side, so we move high to mid - 1.
  5. Repeat the above steps until low and high converge, then return the element at low.

The time complexity of this approach is O(log n) as we are reducing the search space by half in each iteration, and the space complexity is O(1) as we are using constant space.

LeetCode 540 Solutions in Java, C++, Python

class Solution {
    public int singleNonDuplicate(int[] nums) {
        int low = 0, high = nums.length - 1;
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (mid % 2 == 1) {
                mid--; // Ensure mid is always on even index
            }
            if (nums[mid] == nums[mid + 1]) {
                low = mid + 2;
            } else {
                high = mid;
            }
        }
        return nums[low];
    }
}

Interactive Code Editor for LeetCode 540

Improve Your LeetCode 540 Solution

Use the editor below to refine the provided solution for LeetCode 540. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems