🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
\uD83D\uDD34 Check out LeetCode The Hard Way for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our Discord Study Group for live discussion.
\uD83D\uDD34 Check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our [Discord Study Group](https://discord.gg/Nqm4jJcyBf) for live discussion.\n\uD83D\uDFE2 Give a star on [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post if you like it.\n\uD83D\uDD35 Check out [Screencast](https://www.youtube.com/watch?v=UayPePcTQIY&list=PLBu4Bche1aEU-8z7xl3-B9lfw_DJtT_xs&index=21) if you are interested.\n\n---\n\n**Suggested Problems**\n\n- https://leetcode.com/problems/binary-search/\n- https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/\n- https://leetcode.com/problems/find-peak-element/\n- https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/\n\n**Approach: Binary Search**\n\nSee [Binary Search](https://leetcodethehardway.com/tutorials/basic-topics/binary-search) for the tutorial.\n\n```cpp\nclass Solution {\npublic:\n    int singleNonDuplicate(vector<int>& nums) {\n        // init possible boundary\n        int n = nums.size(), l = 0, r = n - 1;\n        while (l < r) {\n            // get the middle one\n            // for even number of elements, take the lower one\n            int m = l + (r - l) / 2;\n            // handle case like [3,3,7,7,10,11,11]\n             m -= m & 1;\n            // exclude m\n            if (nums[m] == nums[m + 1]) l = m + 2;\n            // include m\n            else r = m;\n        }\n        return nums[l];\n    }\n};\n```\n\n```py\nclass Solution:\n    def singleNonDuplicate(self, nums: List[int]) -> int:\n        n = len(nums)\n        l, r = 0, n - 1\n        while l < r:\n            m = (l + r) // 2\n            if m & 1:\n                m -= 1\n            if nums[m] == nums[m + 1]:\n                l = m + 2\n            else:\n                r = m\n        return nums[l]\n```
['Binary Search', 'Python']