Delete Columns to Make Sorted

You are given an array of n strings strs, all of the same length. The strings can be arranged so that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] is arranged as rows abc, bce, cae. You want to delete the columns that are not sorted lexicographically from top to bottom. In the example, columns 0 (a, b, c) and 2 (c, e, e) are sorted, while column 1 (b, c, a) is not, so you would delete column 1. Return the number of columns that you will delete.

30:00

Delete Columns to Make Sorted
easy
Free written solution
Topics
Companies

You are given an array of n strings strs, all of the same length. The strings can be arranged so that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] is arranged as rows abc, bce, cae. You want to delete the columns that are not sorted lexicographically from top to bottom. In the example, columns 0 (a, b, c) and 2 (c, e, e) are sorted, while column 1 (b, c, a) is not, so you would delete column 1. Return the number of columns that you will delete.

Example 1:
Input: {"strs":["cba","daf","ghi"]}
Output: 1
Constraints:
  • n==strs.lengthn == \text{strs.length}

  • 1≤n≤1001 \leq n \leq 100

  • 1≤strs[i].length≤10001 \leq \text{strs}[i].\text{length} \leq 1000

  • strs[i]\text{strs}[i] consists of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"strs":["cba","daf","ghi"]}

Stack the 3 strings into a grid with 3 columns. A column survives only if its letters never go down from top to bottom.

strs as a grid (3 × 3)

0

1

2

0

c

b

a

1

d

a

f

2

g

h

i

·

·

·

sorted columns kept

0

deleted

0

Variables
VariableValue
c-
r-
deleted0
DepthFunction Call
Stack empty
0/11