{"id":4284,"date":"2023-06-30T17:41:55","date_gmt":"2023-06-30T12:11:55","guid":{"rendered":"https:\/\/www.interviewbit.com\/blog\/?p=4284"},"modified":"2023-06-30T18:01:09","modified_gmt":"2023-06-30T12:31:09","slug":"search-in-rotated-sorted-array","status":"publish","type":"post","link":"https:\/\/www.interviewbit.com\/blog\/search-in-rotated-sorted-array\/","title":{"rendered":"Search in Rotated Sorted Array"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<div class=\"gutentoc tocactive nostyle\"><div class=\"gutentoc-toc-wrap\"><div class=\"gutentoc-toc-title-wrap\"><div class=\"gutentoc-toc-title\">Table Of Contents<\/div><div id=\"open\" class=\"text_open\">show<\/div><\/div><div id=\"toclist\"><div class=\"gutentoc-toc__list-wrap\"><ul class=\"gutentoc-toc__list\"><li><a href=\"#problem-statement\">Problem Statement<\/a><\/li><li><a href=\"#naive-approach\">Naive Approach<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-code\">C++ Code<\/a><\/li><li><a href=\"#java-code\">Java Code<\/a><\/li><li><a href=\"#python-code\">Python Code<\/a><\/li><\/ul><li><a href=\"#optimal-approachwith-binary-search\">Optimal Approach(With Binary Search)<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-code\">C++ Code<\/a><\/li><li><a href=\"#java-code\">Java Code<\/a><\/li><li><a href=\"#python-code\">Python Code<\/a><\/li><\/ul><li><a href=\"#practice-problem\">Practice Problem:<\/a><\/li><li><a href=\"#faqs\">FAQs<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#q1-will-the-binary-search-approach-work-if-the-array-has-duplicate-elements\">Q.1: Will the binary search approach work if the array has duplicate elements?<\/a><\/li><li><a href=\"#q2-what-are-the-base-cases-for-this-recursive-approach\">Q.2: What are the base cases for this recursive approach?<\/a><\/li><\/ul><\/ul><\/div><\/div><\/div><\/div>\n\n\n\n<h2 id=\"problem-statement\">Problem Statement<\/h2>\n\n\n\n<p>Given an array of <strong>distinct<\/strong> elements, which is formed from some places rotation of a sorted array, find if a given element is present in the array or not.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img  loading=\"lazy\"  width=\"1024\"  height=\"256\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"distinct elements\"  class=\"wp-image-4427 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/distinct-elements-1024x256.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/distinct-elements-1024x256.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/distinct-elements-300x75.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/distinct-elements-768x192.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/distinct-elements-1536x384.png 1536w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/distinct-elements-2048x512.png 2048w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/distinct-elements-380x95.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/distinct-elements-550x138.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/distinct-elements-800x200.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/distinct-elements-1160x290.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/distinct-elements.png 2400w\" ><\/figure>\n\n\n\n<p><strong>Sample Test Cases :<\/strong><\/p>\n\n\n\n<p><strong>Input 1:<\/strong><\/p>\n\n\n\n<p>a[] = [4, 5, 6, 7, 8, 9, 1, 2, 3]\n\n\n\n<p>sum = 6<\/p>\n\n\n\n<p><strong>Output 1:<\/strong><\/p>\n\n\n\n<p>2<\/p>\n\n\n\n<p><strong>Explanation 1:<\/strong><\/p>\n\n\n\n<p>The value of 2 is found in the array <strong>a[]<\/strong> at index <strong>2<\/strong>.<\/p>\n\n\n\n<p><strong>Input 2:<\/strong><\/p>\n\n\n\n<p>a[] = [4, 5, 6, 7, 8, 9, 1, 2, 3]\n\n\n\n<p>sum = 12<\/p>\n\n\n\n<p><strong>Output 2:<\/strong><\/p>\n\n\n\n<p>-1<\/p>\n\n\n\n<p><strong>Explanation 2:<\/strong><\/p>\n\n\n\n<p>Since the value of 12 is not present in the given array, we return -1.<\/p>\n\n\n\n<h2 id=\"naive-approach\">Naive Approach<\/h2>\n\n\n\n<p>The naive approach to solve this problem is to linearly iterate on the array, and check if the current element is equal to the target element or not.<\/p>\n\n\n\n<p id=\"-code--implementation-\"><strong>Code \/ Implementation:<\/strong><\/p>\n\n\n\n<h3 id=\"c-code\"><span id=\"c-code-2\">C++ Code<\/span><\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">int findInArray(vector &amp;lt; int > &amp;amp; a, int target) {\n  return find(a.begin(), a.end(), target) == a.end() ? -1 : find(a.begin(), a.end(), target) - a.begin();\n}<\/pre>\n\n\n\n<h3 id=\"java-code\"><span id=\"java-code-2\">Java Code<\/span><\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static int findInArray(int[] a, int target) {\n  int found = -1;\n  for (int i = 0; i &amp;lt; a.length; i++) {\n    if (a[i] == target) {\n      found = i;\n      break;\n    }\n  }\n  return found;\n}<\/pre>\n\n\n\n<h3 id=\"python-code\"><span id=\"python-code-2\">Python Code<\/span><\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def findInArray(a, target):\n    for i in range(len(a)):\n        if a[i] == target:\n            return i\n    return -1<\/pre>\n\n\n\n<p id=\"-complexity-analysis-\"><strong>Complexity Analysis:<\/strong><\/p>\n\n\n\n<ul><li>Time Complexity: O(n)<\/li><li>Space Complexity: O(1)<\/li><\/ul>\n\n\n\n<h2 id=\"optimal-approachwith-binary-search\">Optimal Approach(With Binary Search)<\/h2>\n\n\n\n<p>We can solve this problem optimally with a single recursive <strong>Binary Search<\/strong>.<strong> <\/strong>The algorithm is implemented as follows:<\/p>\n\n\n\n<ul><li>Initialize the recursive function with 2 pointers, left = 0, and right = n &#8211; 1.<\/li><li>Find the mid of the range mid = (left + right) \/ 2.<\/li><li>If the range [left, mid] is sorted,<ul><li>If the target lies in that range, recursively go to the range [left, mid].<\/li><li>Else go to the range [mid + 1, right].<\/li><\/ul><\/li><li>Else, we go to the range [mid + 1, right] (since it must be sorted),<ul><li>If the target lies in the range, recursively go to the range [mid + 1, right].<\/li><li>Else go to the range [left, mid].&nbsp;<\/li><\/ul><\/li><\/ul>\n\n\n\n<p id=\"-implementation-\"><strong>Implementation:<\/strong><\/p>\n\n\n\n<h3 id=\"c-code\">C++ Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">int findInArray(vector &amp;lt; int > &amp;amp; a, int left, int right, int target) {\n  if (left > right) {\n    return -1;\n  }\n  int mid = (left + right) \/ 2;\n  if (a[mid] == target) {\n    return mid;\n  }\n  if (a[mid] >= a[left]) {\n    if (target >= a[left] &amp;amp;&amp;amp; target &amp;lt;= a[mid]) {\n      return findInArray(a, left, mid - 1, target);\n    } else {\n      return findInArray(a, mid + 1, right, target);\n    }\n  } else {\n    if (target >= a[mid] &amp;amp;&amp;amp; target &amp;lt;= a[right]) {\n      return findInArray(a, mid + 1, right, target);\n    } else {\n      return findInArray(a, left, mid - 1, target);\n    }\n  }\n}<\/pre>\n\n\n\n<h3 id=\"java-code\">Java Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static int findInArray(int[] a, int left, int right, int target) {\n  if (left > right) {\n    return -1;\n  }\n  int mid = (left + right) \/ 2;\n  if (a[mid] == target) {\n    return mid;\n  }\n  if (a[mid] >= a[left]) {\n    if (target >= a[left] &amp;amp;&amp;amp; target &amp;lt;= a[mid]) {\n      return findInArray(a, left, mid - 1, target);\n    } else {\n      return findInArray(a, mid + 1, right, target);\n    }\n  } else {\n    if (target >= a[mid] &amp;amp;&amp;amp; target &amp;lt;= a[right]) {\n      return findInArray(a, mid + 1, right, target);\n    } else {\n      return findInArray(a, left, mid - 1, target);\n    }\n  }\n}<\/pre>\n\n\n\n<h3 id=\"python-code\">Python Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def findInArray(a, left, right, target):\n    if left > right:\n        return -1\n    mid = (left + right) \/\/ 2\n    if a[mid] == target:\n        return mid\n    if a[mid] >= a[left]:\n        if target >= a[left] and target &amp;lt;= a[mid]:\n            return findInArray(a, left, mid - 1, target)\n        else:\n            return findInArray(a, mid + 1, right, target)\n    else:\n        if target >= a[mid] and target &amp;lt;= a[right]:\n            return findInArray(a, mid + 1, right, target)\n        else:\n            return findInArray(a, left, mid - 1, target)<\/pre>\n\n\n\n<p><strong>Complexity Analysis:<\/strong><\/p>\n\n\n\n<ul><li>Time Complexity: O(log<sub>2<\/sub>n)<\/li><li>Space Complexity: O(1)<\/li><\/ul>\n\n\n\n<h2 id=\"practice-problem\">Practice Problem:<\/h2>\n\n\n\n<ul><li><a rel=\"noreferrer noopener\" href=\"https:\/\/www.interviewbit.com\/problems\/rotated-sorted-array-search\/\" target=\"_blank\">Rotated Sorted Array Search<\/a><\/li><\/ul>\n\n\n\n<h2 id=\"faqs\">FAQs<\/h2>\n\n\n\n<h3 id=\"q1-will-the-binary-search-approach-work-if-the-array-has-duplicate-elements\"><span id=\"q-1-will-the-binary-search-approach-work-if-the-array-has-duplicate-elements\">Q.1: Will the binary search approach work if the array has duplicate elements?<\/span><\/h3>\n\n\n\n<p><strong>Ans:\u00a0<\/strong> The approach will not work if the array has duplicate elements because we won\u2019t be able to decide whether to recurse for the left or right half, in case of duplicates occurring.<\/p>\n\n\n\n<h3 id=\"q2-what-are-the-base-cases-for-this-recursive-approach\"><span id=\"q-2-what-are-the-base-cases-for-this-recursive-approach\">Q.2: What are the base cases for this recursive approach?<\/span><\/h3>\n\n\n\n<p><strong>Ans:<\/strong> If the left pointer, exceeds the right pointer, the function returns -1. Also if the current element, equals the target element, we return the index of this element. These are the base cases of the recursion.<\/p>\n","protected":false},"excerpt":{"rendered":"Problem Statement Given an array of distinct elements, which is formed from some places rotation of a sorted&hellip;\n","protected":false},"author":5,"featured_media":4428,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_daextam_enable_autolinks":"1","csco_singular_sidebar":"","csco_page_header_type":"","csco_appearance_grid":"","csco_page_load_nextpost":"","csco_post_video_location":[],"csco_post_video_location_hash":"","csco_post_video_url":"","csco_post_video_bg_start_time":0,"csco_post_video_bg_end_time":0},"categories":[145],"tags":[144,609],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4284"}],"collection":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/comments?post=4284"}],"version-history":[{"count":5,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4284\/revisions"}],"predecessor-version":[{"id":21009,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4284\/revisions\/21009"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media\/4428"}],"wp:attachment":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media?parent=4284"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/categories?post=4284"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/tags?post=4284"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}