โ† Back to Index

๐Ÿ“š Single Element in a Sorted Array โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Single Element in a Sorted Array problem involves finding the single non-duplicate element in a sorted array where every other element appears exactly twice. The goal is to solve this in O(log N) time using binary search.

๐Ÿงฑ Pattern Template

class Solution {
    public int singleNonDuplicate(int[] nums) {
        int left = 0, right = nums.length - 1;

        while (left < right) {
            int mid = left + (right - left) / 2;

            // Ensure mid is even for comparison
            if (mid % 2 == 1) {
                mid--;
            }

            if (nums[mid] == nums[mid + 1]) {
                left = mid + 2; // Single element is in the right half
            } else {
                right = mid; // Single element is in the left half
            }
        }

        return nums[left]; // Single element
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Single Element in a Sorted Array

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

Explanation:
- The single non-duplicate element is 2.

๐Ÿ’ก Pro Tips