{"id":561,"date":"2025-07-09T17:13:19","date_gmt":"2025-07-09T11:43:19","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=561"},"modified":"2025-07-09T17:26:52","modified_gmt":"2025-07-09T11:56:52","slug":"search-in-rotated-sorted-array-2","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/","title":{"rendered":"Search in Rotated Sorted Array II | Leetcode 81 | Optimal Binary Search"},"content":{"rendered":"\n<p>The &#8220;Search in Rotated Sorted Array II&#8221; problem is a classic coding interview question that tests your understanding of binary search and handling duplicates in arrays. In this blog, we\u2019ll explain the problem, walk you through both brute force and optimal solutions, and make everything easy to understand with code comments, dry runs, and clear explanations.<\/p>\n\n\n\n<p>There is an integer array&nbsp;<code>nums<\/code>&nbsp;sorted in non-decreasing order (not necessarily with&nbsp;<strong>distinct<\/strong>&nbsp;values).<\/p>\n\n\n\n<p>Before being passed to your function,&nbsp;<code>nums<\/code>&nbsp;is&nbsp;<strong>rotated<\/strong>&nbsp;at an unknown pivot index&nbsp;<code>k<\/code>&nbsp;(<code>0 &lt;= k &lt; nums.length<\/code>) such that the resulting array is&nbsp;<code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]<\/code>&nbsp;(<strong>0-indexed<\/strong>). For example,&nbsp;<code>[0,1,2,4,4,4,5,6,6,7]<\/code>&nbsp;might be rotated at pivot index&nbsp;<code>5<\/code>&nbsp;and become&nbsp;<code>[4,5,6,6,7,0,1,2,4,4]<\/code>.<\/p>\n\n\n\n<p>Given the array&nbsp;<code>nums<\/code>&nbsp;<strong>after<\/strong>&nbsp;the rotation and an integer&nbsp;<code>target<\/code>, return&nbsp;<code>true<\/code><em>&nbsp;if&nbsp;<\/em><code>target<\/code><em>&nbsp;is in&nbsp;<\/em><code>nums<\/code><em>, or&nbsp;<\/em><code>false<\/code><em>&nbsp;if it is not in&nbsp;<\/em><code>nums<\/code><em>.<\/em><\/p>\n\n\n\n<p>You must decrease the overall operation steps as much as possible.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/search-in-rotated-sorted-array-ii\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> nums = [2,5,6,0,0,1,2], target = 0<br><strong>Output:<\/strong> true<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> nums = [2,5,6,0,0,1,2], target = 3<br><strong>Output:<\/strong> false<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>1 &lt;= nums.length &lt;= 5000<\/code><\/li>\n\n\n\n<li><code>-10<sup>4<\/sup> &lt;= nums[i] &lt;= 10<sup>4<\/sup><\/code><\/li>\n\n\n\n<li><code>nums<\/code>&nbsp;is guaranteed to be rotated at some pivot.<\/li>\n\n\n\n<li><code>-10<sup>4<\/sup> &lt;= target &lt;= 10<sup>4<\/sup><\/code><\/li>\n<\/ul>\n\n\n\n<p><strong>Follow up:<\/strong>&nbsp;This problem is similar to&nbsp;<a href=\"https:\/\/leetcode.com\/problems\/search-in-rotated-sorted-array\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\">Search in Rotated Sorted Array<\/a>, but&nbsp;<code>nums<\/code>&nbsp;may contain&nbsp;<strong>duplicates<\/strong>. Would this affect the runtime complexity? How and why?<\/p>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-df1fcda4-fd43-4000-9165-ca9bac942e69\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#0-brute-force-solution-linear-search\" style=\"\">Brute Force Solution (Linear Search)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#1-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#3-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#4-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#5-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#6-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#7-optimal-solution-binary-search-with-duplicates-handling\" style=\"\">Optimal Solution (Binary Search with Duplicates Handling)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#8-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#9-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#10-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#11-dry-run\" style=\"\">Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#12-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#13-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/search-in-rotated-sorted-array-2\/#14-final-thoughts\" style=\"\">Final Thoughts<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-brute-force-solution-linear-search\">Brute Force Solution (Linear Search)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>Let\u2019s solve the problem in the most straightforward way:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Scan Each Element:<\/strong><br>Go through the array from start to end.<\/li>\n\n\n\n<li><strong>Check for Target:<\/strong><br>If any element matches the target, return&nbsp;<code>True<\/code>.<\/li>\n\n\n\n<li><strong>Why does this work?<\/strong><br>We check every element, so we won\u2019t miss the target if it\u2019s there.<\/li>\n<\/ol>\n\n\n\n<p>This approach is easy to understand but not efficient for large arrays.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def search(self, nums: List[int], target: int) -&gt; bool:\n        for i in range(len(nums)):               # Scan each index one by one\n            if nums[i] == target:                # If the current element matches target\n                return True                      # Return True immediately\n        return False                             # If not found, return False\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">search<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">], <\/span><span style=\"color: #9CDCFE\">target<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">) -&gt; <\/span><span style=\"color: #4EC9B0\">bool<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)):               <\/span><span style=\"color: #6A9955\"># Scan each index one by one<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[i] == target:                <\/span><span style=\"color: #6A9955\"># If the current element matches target<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">                      <\/span><span style=\"color: #6A9955\"># Return True immediately<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">False<\/span><span style=\"color: #D4D4D4\">                             <\/span><span style=\"color: #6A9955\"># If not found, return False<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We loop through each element in the array.<\/li>\n\n\n\n<li>If we find the target, we return&nbsp;<code>True<\/code>.<\/li>\n\n\n\n<li>If we reach the end without finding it, we return&nbsp;<code>False<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-dry-run\">Dry Run<\/h3>\n\n\n\n<p><strong>Input:<\/strong><br><code>nums = [1], target = 0<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Check 2: not target<\/li>\n\n\n\n<li>Check 5: not target<\/li>\n\n\n\n<li>Check 6: not target<\/li>\n\n\n\n<li>Check 0: found! Return&nbsp;<code>True<\/code><\/li>\n<\/ul>\n\n\n\n<p><strong>Final Output:<\/strong><br><code>True<\/code><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>&nbsp;O(n)<br>We may have to check every element.<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>&nbsp;O(1)<br>Only a variable for looping.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The brute force approach is simple and works for small arrays, but it\u2019s too slow for large inputs.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7-optimal-solution-binary-search-with-duplicates-handling\">Optimal Solution (Binary Search with Duplicates Handling)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<p>We can do much better using a modified binary search:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Binary Search:<\/strong><br>Use two pointers (<code>low<\/code>&nbsp;and&nbsp;<code>high<\/code>) to perform binary search.<\/li>\n\n\n\n<li><strong>Handle Duplicates:<\/strong><br>If&nbsp;<code>nums[low]<\/code>,&nbsp;<code>nums[mid]<\/code>, and&nbsp;<code>nums[high]<\/code>&nbsp;are all equal, we can\u2019t decide which half is sorted, so we shrink the search window from both ends.<\/li>\n\n\n\n<li><strong>Check Sorted Halves:<\/strong>\n<ul class=\"wp-block-list\">\n<li>If the left half is sorted, check if the target is in the left half.<\/li>\n\n\n\n<li>If not, check the right half.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Why does this work?<\/strong><br>Binary search is efficient, and by handling duplicates, we avoid getting stuck in ambiguous situations.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def search(self, nums: List[int], target: int) -&gt; bool:\n        n = len(nums)\n        low = 0\n        high = n - 1\n\n        while low &lt;= high:\n            mid = (low + high) \/\/ 2              # Find the middle index\n\n            if nums[mid] == target:              # If middle element is target, return True\n                return True\n\n            # If we encounter duplicates making it unclear which side is sorted\n            if nums[low] == nums[mid] == nums[high]:\n                high -= 1\n                low += 1\n                continue\n\n            # Check if left half is sorted\n            if nums[low] &lt;= nums[mid]:\n                # Target lies in the left half\n                if nums[low] &lt;= target &lt;= nums[mid]:\n                    high = mid - 1               # Move to the left half\n                else:\n                    low = mid + 1                # Move to the right half\n            # Else, right half is sorted\n            else:\n                # Target lies in the right half\n                if nums[mid] &lt;= target &lt;= nums[high]:\n                    low = mid + 1                # Move to the right half\n                else:\n                    high = mid - 1               # Move to the left half\n\n        return False                             # Target not found\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">search<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">], <\/span><span style=\"color: #9CDCFE\">target<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">) -&gt; <\/span><span style=\"color: #4EC9B0\">bool<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        low = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        high = n - <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> low &lt;= high:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            mid = (low + high) \/\/ <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">              <\/span><span style=\"color: #6A9955\"># Find the middle index<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[mid] == target:              <\/span><span style=\"color: #6A9955\"># If middle element is target, return True<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">True<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># If we encounter duplicates making it unclear which side is sorted<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[low] == nums[mid] == nums[high]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                high -= <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                low += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">continue<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Check if left half is sorted<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[low] &lt;= nums[mid]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Target lies in the left half<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[low] &lt;= target &lt;= nums[mid]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    high = mid - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">               <\/span><span style=\"color: #6A9955\"># Move to the left half<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    low = mid + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Move to the right half<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Else, right half is sorted<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Target lies in the right half<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[mid] &lt;= target &lt;= nums[high]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    low = mid + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Move to the right half<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    high = mid - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">               <\/span><span style=\"color: #6A9955\"># Move to the left half<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">False<\/span><span style=\"color: #D4D4D4\">                             <\/span><span style=\"color: #6A9955\"># Target not found<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We use binary search with pointers&nbsp;<code>low<\/code>&nbsp;and&nbsp;<code>high<\/code>.<\/li>\n\n\n\n<li>If we find the target at&nbsp;<code>mid<\/code>, return&nbsp;<code>True<\/code>.<\/li>\n\n\n\n<li>If duplicates at both ends and middle, shrink the window.<\/li>\n\n\n\n<li>If the left half is sorted, check if the target is in it.<\/li>\n\n\n\n<li>Otherwise, check the right half.<\/li>\n\n\n\n<li>If not found, return&nbsp;<code>False<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-dry-run\">Dry Run<\/h3>\n\n\n\n<p><strong>Input:<\/strong><br><code>nums = [1], target = 0<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>low = 0, high = 6<\/li>\n\n\n\n<li>mid = 3, nums = 0 (target found!)<\/li>\n\n\n\n<li>Return&nbsp;<code>True<\/code><\/li>\n<\/ul>\n\n\n\n<p><strong>Input:<\/strong><br><code>nums = [1], target = 3<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>low = 0, high = 6<\/li>\n\n\n\n<li>mid = 3, nums = 0<\/li>\n\n\n\n<li>Left half is not sorted, right half is sorted.<\/li>\n\n\n\n<li>3 not in right half, move high to mid &#8211; 1.<\/li>\n\n\n\n<li>Continue until low &gt; high.<\/li>\n\n\n\n<li>Return&nbsp;<code>False<\/code><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>&nbsp;O(log n) in the best case, but O(n) in the worst case (when there are many duplicates).<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>&nbsp;O(1)<br>Only a few pointers are used.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The optimal solution is efficient and handles duplicates gracefully. It\u2019s the best approach for interviews and large datasets.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"14-final-thoughts\">Final Thoughts<\/h2>\n\n\n\n<p>The &#8220;Search in Rotated Sorted Array II&#8221; problem is a great example of how to adapt binary search for tricky cases, like duplicates. Start with brute force to understand the basics, then use the optimal solution for best performance.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The &#8220;Search in Rotated Sorted Array II&#8221; problem is a classic coding interview question that tests your understanding of binary search and handling duplicates in arrays. In this blog, we\u2019ll explain the problem, walk you through both brute force and optimal solutions, and make everything easy to understand with code comments, dry runs, and clear<\/p>\n","protected":false},"author":1,"featured_media":564,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[7,27,19],"class_list":{"0":"post-561","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-intermediate","9":"tag-array","10":"tag-binary-search","11":"tag-medium"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/07\/search-in-rotated-sorted-array-II-featured-image-1.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/561","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=561"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/561\/revisions"}],"predecessor-version":[{"id":567,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/561\/revisions\/567"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/564"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=561"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=561"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=561"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}