Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Delete Columns to Make Sorted in Python
Given an array of N lowercase letter strings of equal length, we need to find the minimum number of column deletions required to make all remaining columns sorted in non-decreasing order.
When we delete columns at specific indices, the remaining characters form new columns. Each remaining column must be sorted for the solution to be valid.
Problem Understanding
Consider the array ["abcdef", "uvwxyz"] with deletion indices {0, 2, 3}:
- After deletions:
["bef", "vyz"] - Remaining columns:
["b","v"],["e","y"],["f","z"] - All columns are sorted in non-decreasing order
Algorithm
The approach involves these steps:
- Transform strings into a matrix where each column represents character positions
- Check each column to see if it's already sorted
- Count columns that need deletion (unsorted columns)
- Return the total count
Implementation
class Solution:
def minDeletionSize(self, A):
return sum([1 for col in zip(*A) if list(col) != sorted(col)])
# Test the solution
ob = Solution()
result = ob.minDeletionSize(["cba", "daf", "ghi"])
print("Minimum deletions needed:", result)
Minimum deletions needed: 1
Step-by-Step Example
def solve_step_by_step(A):
print("Input array:", A)
# Create columns using zip
columns = list(zip(*A))
print("Columns:", columns)
deletions_needed = 0
for i, col in enumerate(columns):
is_sorted = list(col) == sorted(col)
print(f"Column {i}: {col} - Sorted: {is_sorted}")
if not is_sorted:
deletions_needed += 1
print(f"Total deletions needed: {deletions_needed}")
return deletions_needed
# Test with example
solve_step_by_step(["cba", "daf", "ghi"])
Input array: ['cba', 'daf', 'ghi']
Columns: (('c', 'd', 'g'), ('b', 'a', 'h'), ('a', 'f', 'i'))
Column 0: ('c', 'd', 'g') - Sorted: True
Column 1: ('b', 'a', 'h') - Sorted: False
Column 2: ('a', 'f', 'i') - Sorted: True
Total deletions needed: 1
How It Works
The solution uses zip(*A) to transpose the array, converting rows to columns. For each column, it compares the original order with the sorted order. If they don't match, the column needs deletion.
Conclusion
This problem is solved by checking each column's sort status and counting unsorted columns. The zip(*A) transpose operation elegantly converts string positions into comparable columns.
