540. Single Element in a Sorted Array LeetCode Solution

In this guide, you will get 540. Single Element in a Sorted Array LeetCode Solution with the best time and space complexity. The solution to Single Element in a Sorted Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Single Element in a Sorted Array solution in C++
  4. Single Element in a Sorted Array solution in Java
  5. Single Element in a Sorted Array solution in Python
  6. Additional Resources
540. Single Element in a Sorted Array LeetCode Solution image

Problem Statement of Single Element in a Sorted Array

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return the single element that appears only once.
Your solution must run in O(log n) time and O(1) space.

Example 1:
Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: nums = [3,3,7,7,10,11,11]
Output: 10

Constraints:

1 <= nums.length <= 105
0 <= nums[i] <= 105

Complexity Analysis

  • Time Complexity: O(\log n)
  • Space Complexity: O(1)

540. Single Element in a Sorted Array LeetCode Solution in C++

class Solution {
 public:
  int singleNonDuplicate(vector<int>& nums) {
    int l = 0;
    int r = nums.size() - 1;

    while (l < r) {
      int m = (l + r) / 2;
      if (m % 2 == 1)
        --m;
      if (nums[m] == nums[m + 1])
        l = m + 2;
      else
        r = m;
    }

    return nums[l];
  }
};
/* code provided by PROGIEZ */

540. Single Element in a Sorted Array LeetCode Solution in Java

class Solution {
  public int singleNonDuplicate(int[] nums) {
    int l = 0;
    int r = nums.length - 1;

    while (l < r) {
      int m = (l + r) / 2;
      if (m % 2 == 1)
        --m;
      if (nums[m] == nums[m + 1])
        l = m + 2;
      else
        r = m;
    }

    return nums[l];
  }
}
// code provided by PROGIEZ

540. Single Element in a Sorted Array LeetCode Solution in Python

class Solution:
  def singleNonDuplicate(self, nums: list[int]) -> int:
    l = 0
    r = len(nums) - 1

    while l < r:
      m = (l + r) // 2
      if m % 2 == 1:
        m -= 1
      if nums[m] == nums[m + 1]:
        l = m + 2
      else:
        r = m

    return nums[l]
# code by PROGIEZ

Additional Resources

See also  70. Climbing Stairs LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.