[Question]: A peak element in a 2D matrix is an element that is strictly greater than all of its adjacent neighbour’s to the left, right, top, and bottom.
Given a 0-indexed m x n
matrix mat
where no two adjacent cells are equal, find any peak element mat[i][j]
and return the length 2 array [i,j]
.You may assume that the entire matrix is surrounded by an outer perimeter with the value -1
in each cell.
Write an algorithm that runs in O(m log(n))
or O(n log(m))
time. Some examples are below
Input: mat = [[1,4],[3,2]] Output: [0,1] Explanation: Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers. Input: mat = [[10,20,15],[21,30,14],[7,16,32]] Output: [1,1] Explanation: Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.
// TC: M*log(N).
// SC: O(1)
func findPeakGrid(_ mat: [[Int]]) -> [Int] {
var startCol = 0, endCol = mat[0].count-1
while startCol <= endCol {
var maxRow = 0, midCol = startCol + (endCol-startCol)/2
for row in 0..<mat.count {
maxRow = mat[row][midCol] >= mat[maxRow][midCol] ? row : maxRow
}
var leftIsBig = midCol-1 >= startCol && mat[maxRow][midCol-1] > mat[maxRow][midCol]
var rightIsBig = midCol+1 <= endCol && mat[maxRow][midCol+1] > mat[maxRow][midCol]
if !leftIsBig && !rightIsBig { // we have found the peak element
return [maxRow, midCol]
} else if (rightIsBig) { // if rightIsBig, then there is an element in 'right' that is bigger than all the elements in the 'midCol',
startCol = midCol+1 //so 'midCol' cannot have a 'peakPlane'
} else {// leftIsBig
endCol = midCol-1
}
}
return []
}
let demoMatrix = [[10,20,15],[21,30,14],[7,16,32]]
let peakElement = findPeakGrid(demoMatrix)
print("Peak Grid is--- ", peakElement)// [1,1]// Explanation: Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.