KatInterview

Stable Grouping and Column Gravity

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingarrayssortingsimulation

Last 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:

  1. All strings beginning with 'T' (Tasks)
  2. All strings beginning with 'U' (Users)
  3. 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 strings
  • grid: A 2D list of integers (may be empty)

Output

Return a list containing exactly two elements:

  1. The reordered list of strings
  2. The grid after applying gravity

Constraints

  • 0 ≤ len(items) ≤ 10^5
  • 0 ≤ M, N ≤ 500 where M is the number of rows and N is the number of columns
  • Grid cells contain integers where 0 means 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.