Given an array nums sorted in non-decreasing order. Every number in the array except one appears twice. Find the single number in the array.
Input :nums = [1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6]
Output:4
Explanation: Only the number 4 appears once in the array.
Input : nums = [1, 1, 3, 5, 5]
Output:3
Explanation: Only the number 3 appears once in the array.
Input :nums = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7]
The idea here is to perform simple comparisons between elements in the array. During iteration, for each element, check if it is equal to either its previous or next element. If it is, then it is not the single element; otherwise, it is the single element.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to find the single non
duplicate element in a sorted array */
int singleNonDuplicate(vector<int>& nums) {
int n = nums.size(); // Size of the array.
/* If array has only one element
return it immediately.*/
if (n == 1) return nums[0];
/* Traverse through the array to find
the single non-duplicate element.*/
for (int i = 0; i < n; i++) {
// Check for the first index.
if (i == 0) {
if (nums[i] != nums[i + 1])
return nums[i];
}
// Check for the last index.
else if (i == n - 1) {
if (nums[i] != nums[i - 1])
return nums[i];
}
// Check for any other index.
else {
if (nums[i] != nums[i - 1] && nums[i] != nums[i + 1])
return nums[i];
}
}
/* Dummy return statement,
should never reach here.*/
return -1;
}
};
int main() {
vector<int> nums = {1, 1, 2, 2, 3, 3, 4};
// Create an object of the Solution class.
Solution sol;
int ans = sol.singleNonDuplicate(nums);
// Print the result.
cout << "The single element is: " << ans << "\n";
return 0;
}
import java.util.*;
class Solution {
/* Function to find the single non
duplicate element in a sorted array */
public int singleNonDuplicate(int[] nums) {
int n = nums.length; // Size of the array.
/* If array has only one element
return it immediately.*/
if (n == 1) return nums[0];
/* Traverse through the array to find
the single non-duplicate element.*/
for (int i = 0; i < n; i++) {
// Check for the first index.
if (i == 0) {
if (nums[i] != nums[i + 1])
return nums[i];
}
// Check for the last index.
else if (i == n - 1) {
if (nums[i] != nums[i - 1])
return nums[i];
}
// Check for any other index.
else {
if (nums[i] != nums[i - 1] && nums[i] != nums[i + 1])
return nums[i];
}
}
/* Dummy return statement,
should never reach here.*/
return -1;
}
public static void main(String[] args) {
int[] nums = {1, 1, 2, 2, 3, 3, 4};
// Create an object of the Solution class.
Solution sol = new Solution();
int ans = sol.singleNonDuplicate(nums);
// Print the result.
System.out.println("The single element is: " + ans);
}
}
class Solution:
""" Function to find the single non
duplicate element in a sorted array """
def singleNonDuplicate(self, nums):
n = len(nums) # Size of the array.
""" If array has only one element
return it immediately."""
if n == 1:
return nums[0]
""" Traverse through the array to find
the single non-duplicate element."""
for i in range(n):
# Check for the first index.
if i == 0:
if nums[i] != nums[i + 1]:
return nums[i]
# Check for the last index.
elif i == n - 1:
if nums[i] != nums[i - 1]:
return nums[i]
# Check for any other index.
else:
if nums[i] != nums[i - 1] and nums[i] != nums[i + 1]:
return nums[i]
""" Dummy return statement,
should never reach here."""
return -1
if __name__ == "__main__":
nums = [1, 1, 2, 2, 3, 3, 4]
# Create an object of the Solution class.
sol = Solution()
ans = sol.singleNonDuplicate(nums)
# Print the result.
print("The single element is:", ans)
class Solution {
/* Function to find the single non
duplicate element in a sorted array */
singleNonDuplicate(nums) {
let n = nums.length; // Size of the array.
/* If array has only one element
return it immediately.*/
if (n === 1) return nums[0];
/* Traverse through the array to find
the single non-duplicate element.*/
for (let i = 0; i < n; i++) {
// Check for the first index.
if (i === 0) {
if (nums[i] !== nums[i + 1])
return nums[i];
}
// Check for the last index.
else if (i === n - 1) {
if (nums[i] !== nums[i - 1])
return nums[i];
}
// Check for any other index.
else {
if (nums[i] !== nums[i - 1] && nums[i] !== nums[i + 1])
return nums[i];
}
}
/* Dummy return statement,
should never reach here.*/
return -1;
}
}
let nums = [1, 1, 2, 2, 3, 3, 4];
// Create an instance of Solution class
let sol = new Solution();
let ans = sol.singleNonDuplicate(nums);
// Print the result
console.log("The single element is:", ans);
Here, the concept of XOR operation will be used to solve this problem. When XOR is applied to two identical numbers, it results in 0 (a XOR a = 0), and XOR of a number with 0 gives the number itself (a XOR 0 = a). Therefore, iterate through the array and perform XOR on each element. Numbers that appear twice will cancel out to zero, leaving only the single number as the answer.
ans
to 0. This variable will eventually hold the XOR result of all elements in the array.ans
variable.#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to find the single non
duplicate element in a sorted array */
int singleNonDuplicate(vector<int>& nums) {
int n = nums.size(); // Size of the array.
int ans = 0;
/* XOR all the elements to find
the single non-duplicate element.*/
for (int i = 0; i < n; i++) {
ans = ans ^ nums[i];
}
/* Return the single non
duplicate element found.*/
return ans;
}
};
int main() {
vector<int> nums = {1, 1, 2, 2, 3, 3, 4};
// Create an object of the Solution class.
Solution sol;
int ans = sol.singleNonDuplicate(nums);
// Print the result.
cout << "The single element is: " << ans << "\n";
return 0;
}
import java.util.*;
class Solution {
/* Function to find the single non
duplicate element in a sorted array */
public int singleNonDuplicate(int[] nums) {
int n = nums.length; // Size of the array.
/* XOR all the elements to find
the single non-duplicate element. */
int ans = 0;
for (int i = 0; i < n; i++) {
ans ^= nums[i];
}
/* Return the single non
duplicate element found. */
return ans;
}
public static void main(String[] args) {
int[] nums = {1, 1, 2, 2, 3, 3, 4};
// Create an object of the Solution class.
Solution sol = new Solution();
int ans = sol.singleNonDuplicate(nums);
// Print the result.
System.out.println("The single element is: " + ans);
}
}
class Solution:
""" Function to find the single non
duplicate element in a sorted array """
def singleNonDuplicate(self, nums):
n = len(nums) # Size of the array.
""" XOR all the elements to find
the single non-duplicate element. """
ans = 0
for num in nums:
ans ^= num
""" Return the single non
duplicate element found. """
return ans
if __name__ == "__main__":
nums = [1, 1, 2, 2, 3, 3, 4]
# Create an object of the Solution class.
sol = Solution()
ans = sol.singleNonDuplicate(nums)
# Print the result.
print("The single element is:", ans)
class Solution {
/* Function to find the single non
duplicate element in a sorted array */
singleNonDuplicate(nums) {
let n = nums.length; // Size of the array.
/* XOR all the elements to find
the single non-duplicate element. */
let ans = 0;
for (let num of nums) {
ans ^= num;
}
/* Return the single non
duplicate element found. */
return ans;
}
}
let nums = [1, 1, 2, 2, 3, 3, 4];
// Create an instance of Solution class
let sol = new Solution();
let ans = sol.singleNonDuplicate(nums);
// Print the result
console.log("The single element is:", ans);
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to find the single non
duplicate element in a sorted array*/
int singleNonDuplicate(vector<int>& nums) {
int n = nums.size(); // Size of the array.
// Edge cases:
if (n == 1) return nums[0];
if (nums[0] != nums[1]) return nums[0];
if (nums[n - 1] != nums[n - 2]) return nums[n - 1];
int low = 1, high = n - 2;
while (low <= high) {
int mid = (low + high) / 2;
// If nums[mid] is the single element:
if (nums[mid] != nums[mid + 1] && nums[mid] != nums[mid - 1]) {
return nums[mid];
}
// We are in the left part:
if ((mid % 2 == 1 && nums[mid] == nums[mid - 1])
|| (mid % 2 == 0 && nums[mid] == nums[mid + 1])) {
// Eliminate the left half:
low = mid + 1;
}
// We are in the right part:
else {
// Eliminate the right half:
high = mid - 1;
}
}
// Dummy return statement:
return -1;
}
};
int main() {
vector<int> nums = {1, 1, 2, 2, 3, 3, 4};
// Create an object of the Solution class.
Solution sol;
int ans = sol.singleNonDuplicate(nums);
// Print the result.
cout << "The single element is: " << ans << "\n";
return 0;
}
import java.util.*;
class Solution {
/* Function to find the single non
duplicate element in a sorted array */
public int singleNonDuplicate(int[] nums) {
int n = nums.length; // Size of the array.
// Edge cases:
if (n == 1) return nums[0];
if (nums[0] != nums[1]) return nums[0];
if (nums[n - 1] != nums[n - 2]) return nums[n - 1];
int low = 1, high = n - 2;
while (low <= high) {
int mid = (low + high) / 2;
// If nums[mid] is the single element:
if (nums[mid] != nums[mid + 1] && nums[mid] != nums[mid - 1]) {
return nums[mid];
}
// We are in the left part:
if ((mid % 2 == 1 && nums[mid] == nums[mid - 1])
|| (mid % 2 == 0 && nums[mid] == nums[mid + 1])) {
// Eliminate the left half:
low = mid + 1;
}
// We are in the right part:
else {
// Eliminate the right half:
high = mid - 1;
}
}
// Dummy return statement:
return -1;
}
public static void main(String[] args) {
int[] nums = {1, 1, 2, 2, 3, 3, 4};
// Create an object of the Solution class.
Solution sol = new Solution();
int ans = sol.singleNonDuplicate(nums);
// Print the result.
System.out.println("The single element is: " + ans);
}
}
class Solution:
""" Function to find the single non
duplicate element in a sorted array """
def singleNonDuplicate(self, nums):
n = len(nums) # Size of the array.
# Edge cases:
if n == 1:
return nums[0]
if nums[0] != nums[1]:
return nums[0]
if nums[n - 1] != nums[n - 2]:
return nums[n - 1]
low, high = 1, n - 2
while low <= high:
mid = (low + high) // 2
# If nums[mid] is the single element:
if nums[mid] != nums[mid + 1] and nums[mid] != nums[mid - 1]:
return nums[mid]
# We are in the left part:
if (mid % 2 == 1 and nums[mid] == nums[mid - 1]) or (mid % 2 == 0 and nums[mid] == nums[mid + 1]):
# Eliminate the left half:
low = mid + 1
# We are in the right part:
else:
# Eliminate the right half:
high = mid - 1
# Dummy return statement:
return -1
nums = [1, 1, 2, 2, 3, 3, 4]
# Create an instance of the Solution class.
sol = Solution()
ans = sol.singleNonDuplicate(nums)
# Print the result.
print(f"The single element is: {ans}")
class Solution {
/* Function to find the single non
duplicate element in a sorted array */
singleNonDuplicate(nums) {
let n = nums.length; // Size of the array.
// Edge cases:
if (n === 1) return nums[0];
if (nums[0] !== nums[1]) return nums[0];
if (nums[n - 1] !== nums[n - 2]) return nums[n - 1];
let low = 1, high = n - 2;
while (low <= high) {
let mid = Math.floor((low + high) / 2);
// If nums[mid] is the single element:
if (nums[mid] !== nums[mid + 1] && nums[mid] !== nums[mid - 1]) {
return nums[mid];
}
// We are in the left part:
if ((mid % 2 === 1 && nums[mid] === nums[mid - 1])
|| (mid % 2 === 0 && nums[mid] === nums[mid + 1])) {
// Eliminate the left half:
low = mid + 1;
}
// We are in the right part:
else {
// Eliminate the right half:
high = mid - 1;
}
}
// Dummy return statement:
return -1;
}
}
let nums = [1, 1, 2, 2, 3, 3, 4];
// Create an object of the Solution class.
let sol = new Solution();
let ans = sol.singleNonDuplicate(nums);
// Print the result.
console.log(`The single element is: ${ans}`);
Q: What is the minimum size of the array, and why?
A: The minimum size of the array is 3, consisting of one single number and one pair. For example, [1, 2, 2] or [1, 1, 2].
Q: What happens if the single number is at the start or end of the array?
A: If the single number is at the start (nums[0]) or end (nums[n-1]), the binary search will naturally identify it because no pairing is possible for these positions.
Q: How would you modify this approach for unsorted arrays?
A: For an unsorted array, the optimal approach is to use the XOR operation. XOR has the property a⊕a=0 and a⊕0=a. XOR all elements in the array to isolate the single number in O(n).
Q: What if the array contains more than one single number?
A: If there are multiple single numbers, XOR won’t work directly. Use a hash map to count occurrences of each element, then return the numbers that appear once.