Single element in sorted array

Binary Search Logic Building Medium

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.

Examples:

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]

Constraints

  •   n == nums.length
  •   1 <= n <= 104
  •   -104 <= nums[i] <= 104

Hints

  • The array is sorted, which means duplicate numbers will appear consecutively. The single number will break this pattern of consecutive duplicates. Use this property to identify the single number efficiently.
  • "Perform a binary search to locate the single number. At each step, check the pairing pattern: If nums[mid] == nums[mid + 1], the single number lies in the unsorted half beyond this pair. Otherwise, if nums[mid] == nums[mid - 1], the single number lies before this pair."

Company Tags

McKinsey & Company GE Healthcare Roche Bain & Company Visa OYO Rooms Intel Alibaba Electronic Arts HCL Technologies Morgan Stanley Rockstar Games Bungie Snowflake Zoho Twilio Uber Walmart Salesforce ARM Dropbox Flipkart Broadcom Zomato Ubisoft TCS Cognizant Accenture Infosys Capgemini Wipro