Count Rows Sorted in Increasing or Decreasing Order
Filed under Samsung
Free read 3 of 3Verify whether 'strictly' increasing/decreasing is required and how single-element rows are handled.
The question
Given a 2D matrix of integers, find the number of rows that are sorted in either strictly increasing or strictly decreasing order.
Constraints
- Matrix dimensions up to 500x500
- Elements can be any integers
Examples
- Input
- matrix = [[1, 2, 3], [3, 2, 1], [1, 3, 2]]
- Output
- 2
- Why
- Row 0 is strictly increasing, Row 1 is strictly decreasing, Row 2 is unsorted.
Approach
Verify whether 'strictly' increasing/decreasing is required and how single-element rows are handled.
Compare every adjacent pair in every row using nested loops.
Iterate through each row and check monotonic properties in a single pass of length O(cols) per row.
Rows with length 1 are typically considered sorted in both directions.
Solution
O(R * C) time, O(1) space
def countSortedRows(matrix):
if not matrix or not matrix[0]: return 0
count = 0
for row in matrix:
if len(row) <= 1:
count += 1
continue
inc = dec = True
for i in range(len(row) - 1):
if row[i] >= row[i+1]: inc = False
if row[i] <= row[i+1]: dec = False
if inc or dec:
count += 1
return count
Tips
- What they are testing: Test rows with single elements, duplicate adjacent elements, and completely empty matrices.
- Common mistake: Confusing strictly increasing/decreasing with non-decreasing/non-increasing.
Related Samsung questions
Collected from public candidate posts and coding forums. Updated Nov 2026.