How to find a single element in a sorted array using binary search

💡 Day 97 of My DSA Challenge – Single Element in a Sorted Array 🔷 Problem : 540. Single Element in a Sorted Array 🔷 Goal : Find the single element that appears only once in a sorted array where all other elements appear exactly twice, in O(log n) time and O(1) space. 🔷 Key Insight : The array is sorted, and elements appear in pairs — except for one. We can use Binary Search on Indices : Check the mid element and compare it with neighbors. If mid is unique → return it. Otherwise, depending on whether the pair is on the left or right and the parity of the remaining elements, move left or right. This works because the single element shifts the pairing pattern in the array, allowing us to discard half the search space each time. 🔷 My Java Approach : 1️⃣ Binary search over array indices. 2️⃣ Compare mid with neighbors to detect the single element. 3️⃣ Adjust search space using parity logic. 🔷 Complexity : Time → O(log n) Space → O(1) Binary search isn’t just for sorted numbers — it can also be applied to patterns and structural properties in arrays. Recognizing such patterns allows efficient solutions even when the array has special constraints. 🚀 #100DaysOfCode #Day97 #LeetCode #DSA #Java #ProblemSolving #BinarySearch #CodingChallenge #Programming #LearnToCode #CodingLife #SoftwareEngineering #Algorithms #DataStructures #TechJourney #CodeEveryday #EngineerMindset #DeveloperJourney #GrowthMindset #CodeNewbie #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories