Peak element in the Array in CIn an Array, the Peak element is the element that is not smaller than its neighbors. It is one of the frequently asked questions in interviews. It is simple. This tutorial shows different approaches we can follow to solve the question efficiently. Example: Suppose, in the Array [10, 20, 15, 23, 14]: 23 is the peak element as it is not smaller than both of its neighbors-15 and 14.
The Naïve approach #1: Traversing the whole ArrayAlgorithm:
Code: Output: Enter the size of the Array: 5 Enter the elements: 8 2 3 9 5 The first Peak element index in the Array: 0 Time complexity: O(n) => One traversal The Naïve approach #2: Finding the largest element in the ArrayIf we find the largest element in the Array, automatically, its neighbors will be smaller than the element. We can use the max() function on the Array. Algorithm:
Code: Output: Enter size of the Array: 5 Enter the elements: 8 2 3 9 5 Peak element index in the Array: 3 Time complexity: O(n) -> One traversal Efficient approach:We saw above that finding the largest element got us one peak element. All the time is taken away to travel through the whole Array, finding the maximum of all the elements. We can break the Array into smaller parts and find the peak element in those parts. Hence, we use the "Divide and conquer" approach. We'll follow the algorithm of Binary search. Algorithm:
Code: Output: Enter size of the Array: 5 Enter the elements: 8 2 3 9 5 Peak element index in the Array: 3 Time complexity: O(Logn) -> Each step, array breaks into half -> Binary search The same code in the Iterative approach:Why do we have to use this approach without the recursion? Both codes are the same, but when we use recursion, an implicit stack is used to keep track of the recursive calls; we can eliminate it using loops. Hence, using this approach the Time complexity isn't changed but space complexity becomes constant. Code: Output: Enter size of the Array: 5 Enter the elements: 8 2 3 9 5 Peak element index in the Array: 3 |