← Questions

Build a target string from the fewest substrings of a source

0
DatabricksCodingLast asked May 2026

A coding interview question asked in Databricks's algorithms (two rounds) round, last asked May 2026. It tests strings, greedy and dynamic programming.

You have a source string and a target string. Build the target by concatenating pieces, where each piece is a substring of the source given by its index range. Use as few pieces as possible, and return the ranges, or report that the target cannot be built.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • min_pieces(source: str, target: str) -> list[tuple[int, int]] | None returns inclusive (start, end) ranges into source whose substrings, joined in order, equal target. Return None if some character of the target does not appear in the source. When several ranges give the same piece, any one is fine.

Example

min_pieces("abcd", "cdab")     -> [(2, 3), (0, 1)]    # "cd" + "ab"
min_pieces("abcab", "bcab")    -> [(1, 4)]            # one piece
min_pieces("abc", "abd")       -> None                # no "d" in the source

Follow-up: delete one character

After one character of the source is deleted, find the new minimum.

source "abcab", delete index 3 -> "abcb"
min_pieces("abcb", "bcab")     -> [(1, 2), (0, 1)]    # "bc" + "ab"

Constraints

  • Lengths up to 10^4 for a simple solution; say how you would handle 10^5 or more.
  • Lowercase letters.

Clarifying questions

  • May the same source range be used more than once? (Yes.)
  • Is the output the ranges or only their count?
  • After a deletion, do you need to answer quickly for many different deletions, or just one?
  • Should ranges be inclusive or half-open?

What a strong answer covers

  • The greedy: at each position of the target, take the longest prefix of the rest that occurs in the source. This is optimal, because every substring of a source substring is also a source substring, so a longer first piece never hurts.
  • Finding that longest match efficiently: O(|source| * |target|) with direct scanning, or a suffix automaton (or suffix array) of the source for O(|source| + |target|).
  • Returning ranges, not just a count, and the impossible case.
  • The deletion follow-up: rebuild the structure on the new source, and discuss whether you can do better when many deletions are queried.
  • Tests: a target equal to the source, a single-character target, repeated characters, an impossible target.

Follow-ups

  • Each piece has a cost that depends on its length. Minimize the total cost instead.
  • Answer the deletion question for every possible deleted index.
  • The source is a set of strings instead of one string.

Where it's asked

What it tests

strings · greedy · dynamic programming

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding