Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find the amplitude and number of waves for the given array
Next article icon

Find the peak index of a given array

Last Updated : 03 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N(> 2) integers, the task is to find the peak index of the array. If the array doesn't contain any peak index, then print -1.

The peak index, say idx, of the given array arr[] consisting of N integers is defined as:

  • 0 < idx < N - 1
  • arr[0] < arr[1] < arr[2] < .... < arr[idx] < .... < arr[N - 2] < arr[N - 1]

Examples:

Input: arr[] = {0, 1, 0}
Output: 1
Explanation: In the given array at index 1, arr[0] < arr[1] and arr[1] > arr[2]. Since index 1 satisfies the given condition, therefore 1 is a peak index of the array.

Input: arr[] = {3, 5, 5, 4, 3, 2, 1}
Output: -1

Naive Approach: The simplest approach is to traverse the array and check for each index, say idx, over the range [1, N - 2] whether the index idx can be the peak index of the array or not. This can be done by checking if all elements to the left and right of this index idx must be in strictly increasing and strictly decreasing order. After checking for all the indices, if there exists any such index, then print that index. Otherwise, print "-1". 

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized based on the fact that the peak index will exist only if the array contains a strictly increasing prefix followed by a strictly decreasing suffix. 
Follow the steps below to solve the problem:

  • Initialize two variables, say ans, to store the index of the peak element of the array.
  • Traverse the given array over the range of indices [1, N - 2], using a variable, say i. If the value of arr[i] is greater than or equal to arr[i + 1], then update ans as i and break out of the loop.
  • If the value of ans is 0 or (N - 1), then print "-1", as there exists no such peak index for the given array.
  • Now, traverse the given array over the range [ans, N - 2] using the variable i and if the value of arr[i] is less than or equal to arr[i + 1], then break out of the loop.
  • After completing the above steps, if the value of i is (N - 1) then print the value of ans as the resultant peak index. Otherwise, print "-1" as there exists no such peak index for the given array.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to find the peak // index for the given array int peakIndex(int arr[], int N) {          // Base Case     if (N < 3)         return -1;      int i = 0;      // Check for strictly     // increasing array     while (i + 1 < N)     {                  // If the strictly increasing         // condition is violated, then break         if (arr[i + 1] < arr[i] ||              arr[i] == arr[i + 1])             break;                      i++;     }      if (i == 0 || i == N - 1)         return -1;      // Stores the value of i, which     // is a potential peak index     int ans = i;      // Second traversal, for     // strictly decreasing array     while (i < N - 1)     {                  // When the strictly         // decreasing condition is         // violated, then break         if (arr[i] < arr[i + 1] ||              arr[i] == arr[i + 1])             break;                      i++;     }      // If i = N - 1, it means that     // ans is the peak index     if (i == N - 1)         return ans;      // Otherwise, peak index doesn't exist     return -1; }  // Driver Code int main() {     int arr[] = { 0, 1, 0 };     int N = sizeof(arr) / sizeof(arr[0]);      cout << peakIndex(arr, N) << "\n";      return 0; }  // This code is contributed by Kingash 
Java
// Java program for the above approach  import java.io.*; import java.util.*;  class GFG {      // Function to find the peak     // index for the given array     public static int peakIndex(int[] arr)     {         int N = arr.length;          // Base Case         if (arr.length < 3)             return -1;          int i = 0;          // Check for strictly         // increasing array         while (i + 1 < N) {              // If the strictly increasing             // condition is violated, then break             if (arr[i + 1] < arr[i]                 || arr[i] == arr[i + 1])                 break;             i++;         }          if (i == 0 || i == N - 1)             return -1;          // Stores the value of i, which         // is a potential peak index         int ans = i;          // Second traversal, for         // strictly decreasing array         while (i < N - 1) {              // When the strictly             // decreasing condition is             // violated, then break             if (arr[i] < arr[i + 1]                 || arr[i] == arr[i + 1])                 break;             i++;         }          // If i = N - 1, it means that         // ans is the peak index         if (i == N - 1)             return ans;          // Otherwise, peak index doesn't exist         return -1;     }      // Driver Code     public static void main(String[] args)     {         int[] arr = { 0, 1, 0 };         System.out.println(peakIndex(arr));     } } 
Python3
# Python3 program for the above approach  # Function to find the peak # index for the given array def peakIndex(arr):          N = len(arr)      # Base Case     if (len(arr) < 3):         return -1      i = 0      # Check for strictly     # increasing array     while (i + 1 < N):          # If the strictly increasing         # condition is violated, then break         if (arr[i + 1] < arr[i] or              arr[i] == arr[i + 1]):             break                  i += 1      if (i == 0 or i == N - 1):         return -1      # Stores the value of i, which     # is a potential peak index     ans = i      # Second traversal, for     # strictly decreasing array     while (i < N - 1):          # When the strictly         # decreasing condition is         # violated, then break         if (arr[i] < arr[i + 1] or              arr[i] == arr[i + 1]):             break                  i += 1      # If i = N - 1, it means that     # ans is the peak index     if (i == N - 1):         return ans      # Otherwise, peak index doesn't exist     return -1  # Driver Code if __name__ == '__main__':          arr = [0, 1, 0]          print(peakIndex(arr))  # This code is contributed by mohit kumar 29 
C#
// C# program for the above approach using System; using System.Collections.Generic;  class GFG{      // Function to find the peak // index for the given array public static int peakIndex(int[] arr) {     int N = arr.Length;      // Base Case     if (arr.Length < 3)         return -1;      int i = 0;      // Check for strictly     // increasing array     while (i + 1 < N)     {                  // If the strictly increasing         // condition is violated, then break         if (arr[i + 1] < arr[i] ||              arr[i] == arr[i + 1])             break;                      i++;     }      if (i == 0 || i == N - 1)         return -1;      // Stores the value of i, which     // is a potential peak index     int ans = i;      // Second traversal, for     // strictly decreasing array     while (i < N - 1)     {                  // When the strictly         // decreasing condition is         // violated, then break         if (arr[i] < arr[i + 1] ||              arr[i] == arr[i + 1])             break;                      i++;     }      // If i = N - 1, it means that     // ans is the peak index     if (i == N - 1)         return ans;      // Otherwise, peak index doesn't exist     return -1; }  // Driver Code static public void Main() {     int[] arr = { 0, 1, 0 };          Console.WriteLine(peakIndex(arr)); } }  // This code is contributed by splevel62 
JavaScript
<script>  // Javascript program for the above approach      // Function to find the peak     // index for the given array     function peakIndex(arr)     {         var N = arr.length;          // Base Case         if (arr.length < 3)             return -1;          var i = 0;          // Check for strictly         // increasing array         while (i + 1 < N) {              // If the strictly increasing             // condition is violated, then break             if (arr[i + 1] < arr[i] || arr[i] == arr[i + 1])                 break;             i++;         }          if (i == 0 || i == N - 1)             return -1;          // Stores the value of i, which         // is a potential peak index         var ans = i;          // Second traversal, for         // strictly decreasing array         while (i < N - 1) {              // When the strictly             // decreasing condition is             // violated, then break             if (arr[i] < arr[i + 1] || arr[i] == arr[i + 1])                 break;             i++;         }          // If i = N - 1, it means that         // ans is the peak index         if (i == N - 1)             return ans;          // Otherwise, peak index doesn't exist         return -1;     }      // Driver Code              var arr = [ 0, 1, 0 ];         document.write(peakIndex(arr));  // This code contributed by Rajput-Ji  </script> 

Output: 
1

 

Time Complexity: O(N)
Auxiliary Space: O(1)


Next Article
Find the amplitude and number of waves for the given array
author
rohit2sahu
Improve
Article Tags :
  • Searching
  • Mathematical
  • Technical Scripter
  • Competitive Programming
  • DSA
  • Arrays
  • Technical Scripter 2020
Practice Tags :
  • Arrays
  • Mathematical
  • Searching

Similar Reads

  • Find the Peak Element in a 2D Array/Matrix
    Given a 2D Array/Matrix mat[][], the task is to find the Peak element. An element is a peak element if it is greater than or equal to its four neighbors, left, right, top and bottom. A peak element is not necessarily the overall maximal element. It only needs to be greater than existing adjacent Mor
    12 min read
  • Find the Target number in an Array
    Finding a number within an array is an operation, in the field of computer science and data analysis. In this article, we will discuss the steps involved and analyze their time and space complexities. Examples: Input: Array: {10, 20, 30, 40, 50} , Target: 30Output: "Target found at index 2" Input: A
    13 min read
  • Find the maximum subarray XOR in a given array
    Given an array of integers. The task is to find the maximum subarray XOR value in the given array. Examples: Input: arr[] = {1, 2, 3, 4}Output: 7Explanation: The subarray {3, 4} has maximum XOR value Input: arr[] = {8, 1, 2, 12, 7, 6}Output: 15Explanation: The subarray {1, 2, 12} has maximum XOR val
    15+ min read
  • Find if a crest is present in the index range [L, R] of the given array
    Given an array arr[] of N distinct elements and an index range [L, R]. The task is to find whether a crest is present in that index range in the array or not. Any element arr[i] in the subarray arr[L...R] is called a crest if all the elements of the subarray arr[L...i] are strictly increasing and al
    6 min read
  • Find the amplitude and number of waves for the given array
    Given an array arr[] of N integers, the task is to find the amplitude and number of waves for the given array. If the array is not a wave array then print -1. Wave Array: An array is a wave array if it is continuously strictly increasing and decreasing or vice-versa. Amplitude is defined as the maxi
    6 min read
  • Find the maximum number of indices that are marked in the given Array
    Given a boolean array a[] of size N and integer K. Initially, all are marked false. We have to choose 2 different indexes having the value false such that a[i] * K ≤ a[j] and mark it as true, the task is to find the maximum number of indexes having a value true in array a[]. Examples: Input: a[] = [
    5 min read
  • Maximum Fixed Point (Value equal to index) in a given Array
    Given an array arr[] of size N, the task is to find the maximum index i such that arr[i] is equal to i. If there is no such index in the array arr[] then print -1. Examples: Input: arr[ ] = {-10, -5, 0, 3, 7}Output: 3Explanation: Only for i=3, arr[3] = 3 Input: arr[ ] = {0, 2, 5, 8, 4}Output: 4 Appr
    4 min read
  • Count of indices in an array that satisfy the given condition
    Given an array arr[] of N positive integers, the task is to find the count of indices i such that all the elements from arr[0] to arr[i - 1] are smaller than arr[i]. Examples: Input: arr[] = {1, 2, 3, 4} Output: 4 All indices satisfy the given condition.Input: arr[] = {4, 3, 2, 1} Output: 1 Only i =
    4 min read
  • Find the indices which will hold the Array sum after given operations
    Given an array arr[], the task is to print the indices that have the highest probability of holding the entire sum of the array after performing the given operations: Choose any two elements say arr[i] and arr[j], store their sum in a variable KAssign K at index of max(arr[i], arr[j]) and assign 0 a
    10 min read
  • Ceiling in a sorted array
    Given a sorted array and a value x, find index of the ceiling of x. The ceiling of x is the smallest element in an array greater than or equal to x. Note: In case of multiple occurrences of ceiling of x, return the index of the first occurrence. Examples : Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences