Amazon Interview Question: Count Negative Integers in Matrix

💡Strategies for Solving This Problem

The Amazon Classic

Got this in my Amazon phone screen. The key detail: matrix is sorted both row-wise and column-wise. That's your hint that binary search or two-pointer will work.

The Setup

Matrix like this:

[-5, -4, -3,  1]
[-3, -2,  0,  2]
[-1,  0,  1,  3]
[ 1,  2,  3,  4]

Count negative numbers. Naive: check every cell = O(n×m). We can do better.

Approach 1: Start Bottom-Left (My Solution)

Start at bottom-left corner. Why? Because:

  • Moving right → numbers increase
  • Moving up → numbers decrease

If current number is negative, entire column above is negative. Count and move right. If positive, move up.

This is O(n+m) time - way better than O(n×m).

Approach 2: Binary Search Per Row

For each row, binary search for the first non-negative number. Count negatives in that row.

O(n log m) time. Works but slower than two-pointer approach.

My Interview

I initially tried to do something complex with diagonals. My interviewer said "Start simple - what about the corners?" That hint saved me. Always consider the corners in matrix problems.

Scroll to Top