Single Element in a Sorted Array
Explore how to find the single non-duplicate element in a sorted array using a modified binary search approach. Understand the problem constraints and implement an O(log n) time and O(1) space solution by analyzing paired elements and their indices. This lesson helps you develop problem-solving skills to efficiently solve interview questions involving arrays and binary search.
We'll cover the following...
Statement
You are given a sorted array of integers, nums, where all integers appear twice except for one. Your task is to find and return the single integer that appears only once.
The solution should have a time complexity of or better and a space complexity of .
Constraints:
-
nums.length -
nums[i]
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps us to check if you’re solving the correct problem:
Single Element in a Sorted Array
What is the output if the following array is provided as input?
[1, 1, 2, 2, 3, 4, 4]
1
3
2
4
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in main.js in the following coding playground. We have provided a useful code template in the other file that you may build on to solve this problem.
export function singleNonDuplicate(nums) {// Replace this placeholder return statement with your codereturn -1;}