1201. Keyed Column Cipher

Medium3.5 points estimatedStringCustom ComparatorSorting

A pen-pal club scrambles its notes with a keyed column cipher. The note text is written row by row into a grid with key.length columns, so the first row holds the first key.length letters, the next row the following ones, and the last row may be shorter. Each column is then read from top to bottom.

The columns are read out in the order given by key: column j is ranked by the letter key[j] in ascending alphabetical order, and when two columns have the same key letter the one with the smaller index goes first. Return the concatenation of all columns in that order. A column can be empty when text is shorter than key.

Here 1 <= text.length <= 10^4, 1 <= key.length <= 100, and both strings use lowercase letters. Sorting the columns and copying each one runs in O(n + k log k) time and O(n) space.

Example 1

Input:
text = "meetmeatnoon", key = "zebra"
Output:
"moeteantnmeo"
Explanation:

With key zebra the columns are meo, ean, et, tn and mo (in column order); sorting by key letters a, b, e, r, z reads columns 4, 2, 1, 3, 0, giving mo + et + ean + tn + meo.

Example 2

Input:
text = "abcdefgh", key = "bca"
Output:
"cfadgbeh"
Explanation:

The grid has columns adg, beh and cf; the key letters b, c, a put them in the order cf, adg, beh.

Example 3

Input:
text = "quietly", key = "k"
Output:
"quietly"
Explanation:

A one-letter key makes a single column, which is the text itself.

Constraints

1 ≤ text.length ≤ 104

1 ≤ key.length ≤ 100

text and key contain lowercase letters only

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n + k log k)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…