Given MxN matrix, this is O(MN)
, which is optimal.
INIT rowMin = [ +Infinify ] xM
INIT colMax = [ -Infinity ] xN
FOR r = 1..M
FOR c = 1..N
rowMin[r] = MIN(rowMin[r], mat[r][c])
colMax[c] = MAX(colMax[c], mat[r][c])
FOR r = 1..M
FOR c = 1..N
IF mat[r][c] == rowMin[r] == colMax[c]
DECLARE saddlePoint(r, c)
Why is this optimal?
Because there are MxN values, and they each need to be looked at, so for your answer to be certain (i.e. not probabilistic), the lowerbound is O(MN)
.
Can this be optimized further?
You can optimize this a bit. It'll still be O(MN)
, but instead of finding the maximum/minimum values, you find their indices instead. This can make the second phase O(M)
in the best case (i.e. when there's a unique min/max in a row/column).
Note that in the worst case, there are O(MN)
saddle points: that's when the numbers in the array are all equal.