Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program for Number of local extrema in an array
In this article, we will learn a Python program to find the number of local extrema in an array.
A local extrema is an element that is either a local maximum (greater than both neighbors) or a local minimum (less than both neighbors). The first and last elements cannot be extrema since they don't have two neighbors.
What are Local Extrema?
Consider an array element at position i. It is a local extrema if:
Local Maximum:
array[i] > array[i-1]andarray[i] > array[i+1]Local Minimum:
array[i] < array[i-1]andarray[i] < array[i+1]
Algorithm
Following are the steps to find local extrema ?
Traverse the array from index 1 to n-2 (exclude first and last elements)
For each element, check if it's greater than both neighbors (local maximum)
Check if it's less than both neighbors (local minimum)
Count both types and return the total count
Implementation Using For Loop
def findExtrema(arr):
"""
Find the number of local extrema in an array.
Args:
arr: List of numbers
Returns:
int: Count of local extrema
"""
if len(arr) < 3:
return 0
count = 0
# Check each element except first and last
for i in range(1, len(arr) - 1):
# Check if current element is local maximum
if arr[i] > arr[i-1] and arr[i] > arr[i+1]:
count += 1
# Check if current element is local minimum
elif arr[i] < arr[i-1] and arr[i] < arr[i+1]:
count += 1
return count
# Test with sample array
arr = [5, 0, 1, 2, 1, 0, 3, 4, 1, 2]
print("Array:", arr)
print("Number of local extrema:", findExtrema(arr))
# Test with edge cases
print("Empty array:", findExtrema([]))
print("Single element:", findExtrema([5]))
print("Two elements:", findExtrema([1, 2]))
Array: [5, 0, 1, 2, 1, 0, 3, 4, 1, 2] Number of local extrema: 4 Empty array: 0 Single element: 0 Two elements: 0
Alternative Implementation
Using boolean arithmetic for concise code ?
def findExtremaCompact(arr):
"""Compact version using boolean arithmetic."""
if len(arr) < 3:
return 0
count = 0
for i in range(1, len(arr) - 1):
# Boolean expressions return 1 if True, 0 if False
is_max = (arr[i] > arr[i-1]) and (arr[i] > arr[i+1])
is_min = (arr[i] < arr[i-1]) and (arr[i] < arr[i+1])
count += is_max + is_min
return count
# Test the compact version
arr = [1, 3, 2, 4, 1, 5, 2]
print("Array:", arr)
print("Local extrema:", findExtremaCompact(arr))
Array: [1, 3, 2, 4, 1, 5, 2] Local extrema: 4
Complexity Analysis
| Metric | Complexity | Explanation |
|---|---|---|
| Time Complexity | O(n) | Single pass through the array |
| Space Complexity | O(1) | Only using constant extra space |
Conclusion
Local extrema detection requires checking each interior element against its neighbors. The algorithm runs in linear time and constant space, making it efficient for large arrays.
