{"id":6616,"date":"2018-10-14T19:57:24","date_gmt":"2018-10-14T14:27:24","guid":{"rendered":"https:\/\/java2blog.com\/?p=6616"},"modified":"2021-01-26T13:49:39","modified_gmt":"2021-01-26T08:19:39","slug":"find-peak-element-array","status":"publish","type":"post","link":"https:\/\/java2blog.com\/find-peak-element-array\/","title":{"rendered":"Find peak element in the array"},"content":{"rendered":"<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#Problem\">Problem<\/a><\/li><li><a href=\"#Solution\">Solution<\/a><\/li><\/ul><\/div>\n<blockquote><p>If you want to practice data structure and algorithm programs, you can go through <a href=\"http:\/\/www.java2blog.com\/data-structure-and-algorithm-interview-questions-in-java.html\" target=\"_blank\" rel=\"noopener noreferrer\">100+ data structure and algorithm programs<\/a>.<\/p><\/blockquote>\n<p>In this post, we will see how to find peak element in the array.<\/p>\n<hr \/>\n<h2><span id=\"Problem\"><span style=\"color: #800000\">Problem<\/span><\/span><\/h2>\n<p>Given an array of integers. find the peak element in the array.<br \/>\n<code> Peak Element<\/code> is the element of the <a href=\"https:\/\/java2blog.com\/category\/array\" rel=\"noopener noreferrer\" target=\"_blank\">array<\/a> which is <em><code>GREATER THAN \/ EQUAL<\/code><\/em> TO its neighbours, that is, for an element at <code>i<\/code> th index, the neighbour elements at index <code>i-1<\/code> &amp; <code>i+1<\/code> must be greater than equal to element at <code>i<\/code> th position.<br \/>\nNow<\/p>\n<p>An array can have several peak elements, we need to output any one of them.<\/p>\n<hr \/>\n<h2><span id=\"Solution\"><span style=\"color: #800000\">Solution<\/span><\/span><\/h2>\n<p>The basic approach to this problem would be iterate through the whole array and at every <strong><em>i<\/em> <\/strong>th element check the condition <code>arr[i-1] = arr[i+1]<\/code>.<\/p>\n<ul>\n<li>For an array with equal numbers, every element will be peak element.<\/li>\n<li>For corner elements the conditions gets slightly tweaked as they will have only one neighbour, that is,<br \/>\nfor extreme left element we just need to check if <code>arr[i+1] &lt;= arr[i]<\/code>.<br \/>\nfor extreme right element we just need to check <code>arr[i-1] &lt;= arr[i]<\/code>.<\/li>\n<p>The worst time complexity of this approach would be <code>O(n)<\/code>.<\/p>\n<p><span style=\"text-decoration: underline\"><strong>Efficient Approach:<\/strong><\/span><\/p>\n<p>We can use a Divide and conquer approach for the same which uses an algorithm similar to Binary search where a condition is checked with the middle element and depending on the result we search for our answer in one of the halves of the initial array. As the number of elements gets half on every call, this will have the worst time complexity of <strong> O(log(n)).<\/strong><\/p>\n<p><span style=\"text-decoration: underline\"><strong>Algorithm<\/strong> :<\/span><br \/>\nWe compare middle element of the array with its neighbours and if it is greater than or equal to its neighbours. If the middle element is greater than or equal to its neighbours, we return it.<br \/>\nIf the element is smaller than its left neighbour then it is sure that the peak element lies in left.<\/p>\n<p><strong>WHY?<\/strong><\/p>\n<p>Consider an Array,<\/p>\n<p style=\"text-align: left\">\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 <code>int[] arr = {a1, a2, a3, a4, a5, a6, a7};<\/code><br \/>\nThere arise 2 cases when left neighbour<code>(a3)<\/code> is greater than middle element<code>(a4)<\/code> i.e. <code>a3 &gt; a4<\/code>:<br \/>\n<strong>Case-1<\/strong> : if the left neighbour<code>(a3)<\/code> is corner, then this is our peak element.<br \/>\n<strong>Case-2<\/strong> : if left element is not the corner element.Here again 2 possibilities arise, that is,<\/p>\n<ol>\n<li style=\"text-align: left\">if <code>a2 &gt; a3<\/code>\u00a0, then this becomes the same recursive subproblem which we discussed<br \/>\nabove and its result will eventually be calculated recursively.<\/li>\n<li>if <code>a2 &lt; a3<\/code>, then again <code>a3<\/code> is our peak element because, <code>a3 &gt; a2<\/code>\u00a0 &amp;\u00a0\u00a0<code>a3 &gt; a4<\/code>, i.e. <code>a3<\/code> is greater than or equal to its neighbours.<\/li>\n<\/ol>\n<p>The same procedure is followed the case when right neighbour (a5) is greater than middle element.<\/p>\n<pre class=\"java\" name=\"code\" title=\"PeakElement.java\">\npackage org.arpit.java2blog;\n\nimport java.util.Scanner;\n\npublic class PeakElement {\n\n    public static void main(String[] args) {\n\n        Scanner scn = new Scanner(System.in);\n        int[] arr = new int[scn.nextInt()];\n\n        for (int i = 0; i &lt; arr.length; i++) {\n            arr[i] = scn.nextInt();\n        }\n\n        int peakIndex = solve(0, arr.length - 1, arr);\n\n        System.out.print(\"arr[]: {\");\n        for (int i = 0; i &lt; arr.length; i++) {\n            System.out.print(\" \"+arr[i]);\n        }\n\n        System.out.println(\" }\");\n        System.out.println(\"Peak element is : \" + arr[peakIndex] +\n                                   \" found at index \" + peakIndex);\n\n    }\n\n    public static int solve(int start, int end, int[] arr) {\n\n        \/\/ finding mid for dividing the array into two parts\n        int mid = (start + end) \/ 2;\n\n        \/\/ if the mid element is not the corner element and it is greater \n                \/\/ than or equal to its neighbours\n        if ((mid &gt; 0 && mid &lt; arr.length - 1) && (arr[mid] &gt;= \n                     arr[mid + 1] && arr[mid] &gt;= arr[mid - 1])) {\n            return mid;\n        }\n\n        \/\/ if the mid element is left corner element and it is greater  \n                \/\/than or equal to its right neighbour.\n\n        else if (mid == 0 && mid!= arr.length-1 && arr[mid] &gt;= \n                         arr[mid + 1])\n        {\n            return mid;\n        }\n\n        \/\/ if the mid element is right corner element and it is greater \n                \/\/ than or equalto its left neighbour.\n\n        else if (mid == arr.length - 1 && mid!= 0 && \n                         arr[mid - 1] &lt;= arr[mid]) \n        {\n            return mid;\n        }\n\n        \/\/ if mid element is smaller than its left neighbour, \n                \/\/ then peak element will be in left side for sure.\n\n        else if (mid != 0 && arr[mid - 1] &gt; arr[mid]) \n        {\n            return solve(start, mid - 1, arr);\n        } \n        else \n        {\n            if(mid + 1 &lt;= arr.length-1)\n            {\n               return solve(mid + 1, end, arr);\n            }\n        }\n        \/\/ in case the array has only one element then than is the \n                \/\/peak element\n        return 0;\n    }\n\n}\n<\/pre>\n<p>When you run above program, you will get below output.<\/p>\n<div class=\"content-box-green\">\n4 10 20 40 15<br \/>\narr[]: { 10 20 40 15 }<br \/>\nPeak element is : 40 found at index 2\n<\/div>\n<p>That&#8217;s all about how to find peak element in the array.<br \/>\nComment in case of any doubt or edit. Happy Learning &#x1f642;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Table of ContentsProblemSolution If you want to practice data structure and algorithm programs, you can go through 100+ data structure and algorithm programs. In this post, we will see how to find peak element in the array. Problem Given an array of integers. find the peak element in the array. Peak Element is the element [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":12587,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[11,13],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/6616"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=6616"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/6616\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/12587"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=6616"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=6616"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=6616"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}