KatInterview

Stable Unique Values and Chained Word Stitching

Arrays & HashingAuto-graded · 19 test cases
EasyAuto-gradedArrays & Hashinghash-setstringsdeduplication

Last updated

Tests order-preserving deduplication with a set and a sequential string merge that collapses a single shared boundary character, including empty-string edge cases.

Stable Unique Values and Chained Word Stitching

Write a single function that solves two small, independent tasks and returns both answers together.

Task A: Keep first occurrences

Given a list of integers values, build a new list that contains each distinct value exactly once. A value must appear at the position of its first occurrence in the input, and the relative order of these first occurrences must match the input.

Task B: Stitch words in order

Given a list of lowercase strings pieces, build one string by processing the pieces strictly from left to right, in the order given. Do not reorder them.

  1. Start with the first piece as the current result. If pieces is empty, the result is the empty string.
  2. For each following piece:
    • If both the current result and the piece are non-empty, and the last character of the result equals the first character of the piece, append the piece without its first character (the shared character is written only once).
    • Otherwise, append the piece unchanged.

Only a single character can ever be shared at a boundary. Never look for longer suffix/prefix overlaps.

Output

Return a two-element list [unique_values, stitched]:

  • unique_values: the list from Task A
  • stitched: the string from Task B

Constraints

  • 0 <= len(values) <= 10^5
  • 0 <= len(pieces) <= 10^4
  • Values are integers.
  • Pieces consist of lowercase English letters and may be empty strings.
  • The total number of characters across all pieces is at most 10^5.
  • Pieces are merged in the given order only; no reordering.

Examples

Example 1

Input: unique_and_stitch([1, 2, 1, 3, 2, 4], ['abc', 'rgn', 'ctr'])

Output: [[1, 2, 3, 4], 'abcrgnctr']

Example 2

Input: unique_and_stitch([5, 5, 5, 2, 2, 1], ['cat', 'top', 'pear'])

Output: [[5, 2, 1], 'catopear']

Example 3

Input: unique_and_stitch([], [])

Output: [[], '']

Hints

Hint 1

For the first task, scan once while keeping a set of values already seen; append a value to the output only when it is not in the set yet.

Hint 2

For the second task, the only thing that matters at each step is the last character of what you have built so far and the first character of the next piece.

Hint 3

Guard against empty strings before indexing the last or first character, and remember that a one-letter piece that overlaps contributes nothing new.