Assign Persistent Table Column Identifiers
Arrays & HashingAuto-graded · 21 test casesLast updated
Process sequential database schema snapshots to assign permanent, case-insensitive unique column aliases with automatic collision resolution.
You are building a schema tracking system that generates consistent, case-insensitive column identifiers across updates for multiple database tables.
You are given a list of schema updates, calls. Each item in calls is a list of strings where the first element is a case-sensitive tableName, followed by zero or more column names representing the ordered list of columns in the current snapshot:
[tableName, column1, column2, ...]
For each snapshot call, return a list containing the finalized identifier assigned to each input column in that call, maintaining their original order.
Identifier Rules and Collision Resolution
- Dot Normalization: The initial candidate for an incoming column name is created by converting all period characters (
.) into underscores (_). - Table Isolation: Each table tracks its state independently.
- Case-Insensitive Uniqueness: No two distinct columns assigned to the same table can share the same case-insensitive identifier (e.g.,
A_Banda_bcollide). - Permanent Assignment: Once a column name is assigned an identifier in a table, that assignment is fixed forever. Even if the column is dropped, reordered, or reintroduced in later calls, its identifier never changes.
- Reserved Identifiers: Once an identifier is assigned, its lowercased string remains permanently reserved for that table. Dropped columns do not release their reserved identifiers.
- Collision Handling:
- If an unassigned column's candidate identifier (converted to lowercase) is not yet reserved in that table, it takes that candidate identifier directly.
- If the candidate identifier is already reserved, append
_1,_2,_3, ..., attempting consecutive positive integer suffixes in increasing order until an unreserved candidate (case-insensitively) is found. - The final identifier preserves the character casing of the candidate (e.g., if candidate
A_Bcollides twice, it receivesA_B_2). - Natural suffixes in original names (like
a_b_1) are treated as plain text. Ifa_b_1collides, its next candidate isa_b_1_1(nota_b_2).
Constraints
callscontains at most 1,000 sublists.- Total number of column occurrences across all calls is at most 10,000.
- Names (table and column) consist of non-empty ASCII strings of at most 100 characters containing letters, digits, dots, and underscores.
- Column names within a single input call are unique (exact match).
- Table names are matched exactly (case-sensitive).
Notes
- If a call contains only a table name with zero columns, return an empty list
[]for that call.
Examples
Example 1
Input: rename_columns([['T', 'a.b', 'a_b', 'a_b_1'], ['T', 'a_b'], ['T', 'a_b_1', 'a.b', 'A.B'], ['U', 'a_b']])
Output: [['a_b', 'a_b_1', 'a_b_1_1'], ['a_b_1'], ['a_b_1_1', 'a_b', 'A_B_2'], ['a_b']]
Hints
Hint 1
Maintain two persistent data structures per table: a mapping from original column name to assigned identifier, and a set of all lowercased reserved identifiers.
Hint 2
When a column is seen for the first time, replace dots with underscores to form the base candidate.
Hint 3
Incrementally test candidate suffixes (_1, _2, etc.) against the lowercased reserved set until an available identifier is found, then store and return it.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To satisfy the requirements, we need to maintain persistent state for each individual table across all input calls. Specifically, each table requires two structures:
- Column Mapping (
assignments): A dictionary mapping the exact, case-sensitive original column string to its assigned finalized identifier. - Reserved Set (
reserved): A hash set storing the lowercase versions of all identifiers assigned so far within this table.
For each snapshot:
- Extract the
tableNameand the list of column names. - Initialize state for new tables if not already present.
- Iterate through each column name in the snapshot:
- Already Seen: If the column exists in
assignments, immediately retrieve its stored identifier. - New Column:
- Transform dots to underscores:
candidate = col.replace('.', '_'). - Initialize
effective = candidate. - Check if
effective.lower()is inreserved. While it is present, form a new stringf"{candidate}_{suffix}"forsuffix = 1, 2, 3, ...until finding an available string. - Save
assignments[col] = effectiveand addeffective.lower()toreserved.
- Transform dots to underscores:
- Already Seen: If the column exists in
- Collect and append the snapshot's output array to the final result list.
Complexity Analysis
-
Time Complexity:
- For previously assigned columns, lookup takes $\mathcal{O}(L)$ time where $L$ is the string length.
- For new columns, probing against
reservedtakes $\mathcal{O}(L)$ per attempt. In the worst case where multiple similar column names generate collisions (e.g.,a.b,a_b,A.b,A_B), searching for a free suffix takes up to $k$ iterations for the $k$-th collision. - Overall time complexity is $\mathcal{O}(N^2 \cdot L)$ in the worst case, where $N$ is the total number of unique column registrations and $L \le 100$ is the max string length. Given $N \le 10,000$, this readily runs well within execution limits.
-
Space Complexity: $\mathcal{O}(N \cdot L)$ to store mapped columns, reserved identifier sets, and the output structure.
Python Reference Solution
from typing import List
def rename_columns(calls: List[List[str]]) -> List[List[str]]:
# Storage for per-table state:
# table_name -> (assignments_dict, reserved_set)
table_states = {}
results = []
for row in calls:
table_name = row[0]
columns = row[1:]
if table_name not in table_states:
table_states[table_name] = ({}, set())
assignments, reserved = table_states[table_name]
current_output = []
for col in columns:
if col not in assignments:
candidate = col.replace('.', '_')
effective = candidate
suffix_index = 1
while effective.lower() in reserved:
effective = f"{candidate}_{suffix_index}"
suffix_index += 1
assignments[col] = effective
reserved.add(effective.lower())
current_output.append(assignments[col])
results.append(current_output)
return results