Stable Grouping and Column Gravity
Arrays & HashingAuto-graded · 18 test casesLast updated
Tests stable partitioning of categorized strings and simulating gravity on independent grid columns
You are given a list of labeled strings and a 2D integer grid. Your task is to perform two independent transformations and return both results.
Task 1: Stable Category Grouping
Given a list of strings, reorder them into three groups based on their first character:
- All strings beginning with
'T'(Tasks) - All strings beginning with
'U'(Users) - All other strings (Systems)
Within each group, preserve the original relative order of elements (stable partitioning).
Task 2: Apply Column Gravity
Given a grid of integers where 0 represents an empty cell and any non-zero integer represents an item, simulate gravity acting downward on each column independently. All items fall straight down until they reach the bottom of the grid or land on another item. Empty cells rise to the top of each column. The relative top-to-bottom order of items within each column must be preserved.
Input
items: A list of stringsgrid: A 2D list of integers (may be empty)
Output
Return a list containing exactly two elements:
- The reordered list of strings
- The grid after applying gravity
Constraints
0 ≤ len(items) ≤ 10^50 ≤ M, N ≤ 500where M is the number of rows and N is the number of columns- Grid cells contain integers where
0means empty - All rows in the grid have the same length (rectangular grid)
- Your solution should run in O(len(items)) time for the list and O(M × N) time for the grid
Examples
Example 1
Input: group_and_settle(['U1', 'T1', 'S1', 'T2', 'U2'], [[0, 1], [0, 0], [2, 0]])
Output: [['T1', 'T2', 'U1', 'U2', 'S1'], [[0, 0], [0, 0], [2, 1]]]
Example 2
Input: group_and_settle(['T1', 'T2', 'U1', 'S1'], [[1, 0, 2], [0, 3, 0], [4, 0, 5]])
Output: [['T1', 'T2', 'U1', 'S1'], [[0, 0, 0], [1, 0, 2], [4, 3, 5]]]
Example 3
Input: group_and_settle([], [])
Output: [[], []]
Hints
Hint 1
For the string list, you don't need to sort—just collect items into three separate buckets as you scan through once, then concatenate them in the correct order.
Hint 2
Each column in the grid is independent. Process them one at a time: extract all non-zero values in order, fill the column with zeros, then place the values at the bottom.
Hint 3
Be careful with edge cases: empty grids, strings that don't start with T or U, and columns that are already settled or completely empty.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines two independent transformations, each leveraging stable partitioning.
Part 1: Stable Category Grouping
Instead of sorting, we use a bucket collection strategy:
- Scan through the input list once
- Place each string into one of three buckets based on its first character:
- Bucket 1: strings starting with
'T' - Bucket 2: strings starting with
'U' - Bucket 3: all other strings (including those starting with
'S', empty strings, or any other prefix)
- Bucket 1: strings starting with
- Concatenate the buckets in order: tasks + users + systems
This preserves relative order within each category because we append items in the order we encounter them. The result is a stable three-way partition.
Part 2: Column Gravity Simulation
Each column operates independently since items only fall vertically:
- For each column, extract all non-zero values from top to bottom, maintaining their order
- Clear the entire column by filling it with zeros
- Place the extracted values starting from row
(total_rows - count_of_values)downward
This simulates gravity settling items to the bottom while preserving their relative vertical order. Items cannot pass through each other, so the top-to-bottom sequence stays intact.
Important: We create a copy of the grid to avoid mutating the input.
Why It Works
- Grouping: Each item goes into exactly one bucket in input order, so relative order within categories is preserved. Concatenation ensures all T items come before all U items, which come before all other items.
- Gravity: After settling, a column with k items must have them in the bottom k positions with no gaps (since they've fallen as far as possible). Since items can't pass through each other, they maintain their original top-to-bottom order. Our algorithm directly constructs this final state.
Complexity
- Time: O(N) for grouping N items + O(M × N) for processing M × N grid cells = O(N + M × N)
- Space: O(N) for output list + O(M × N) for copied grid = O(N + M × N)
Both time and space meet the stated constraints.
Edge Cases Handled
- Empty input list returns empty grouped list
- Empty grid returns empty grid
- Grid with zero rows or zero columns
- Strings with unexpected prefixes (not T, U, or S) go into the systems bucket
- Empty strings are handled safely by
startswith() - Columns already settled or completely empty work without special cases
Solution Code
from typing import List
def group_and_settle(items: List[str], grid: List[List[int]]) -> List:
# Part 1: Collect items into three buckets
tasks = []
users = []
systems = []
for item in items:
if item.startswith("T"):
tasks.append(item)
elif item.startswith("U"):
users.append(item)
else:
systems.append(item)
grouped = tasks + users + systems
# Part 2: Apply gravity to each column independently
result = [row[:] for row in grid]
rows = len(result)
cols = len(result[0]) if rows > 0 else 0
for col in range(cols):
# Collect non-zero values from this column in order
values = [grid[row][col] for row in range(rows) if grid[row][col] != 0]
# Clear the column and place values at the bottom
num_values = len(values)
start_row = rows - num_values
for row in range(rows):
if row < start_row:
result[row][col] = 0
else:
result[row][col] = values[row - start_row]
return [grouped, result]