← Questions

Compress URL path segments under token limits

0
StripeCodingLast asked Nov 2023

A coding interview question asked in Stripe's onsite coding (debug, integrate, build) round, last asked Nov 2023. It tests strings and greedy.

A path such as alpha.beta.gamma/delta.echo has major parts separated by / and minor parts separated by .. A word is compressed by keeping its first and last letters and replacing the middle with the count of letters removed (alpha becomes a3a).

  1. Compress every minor part.
  2. Each major part may produce at most m tokens: compress its first minor parts one by one and merge the rest into one final token, compressed from the original letters.
  3. The whole path may produce at most t tokens: every major part keeps at least one, and the remaining budget is handed out from left to right.

Clarifying questions

  • How are short words compressed: does ab stay ab, and does abc become a1c?
  • In part 2, are the remaining minor parts joined without the . before they are compressed into one token?
  • Does the output keep the / and . separators, or is it a list of tokens?
  • In part 3, what if t is smaller than the number of major parts?
  • How are empty segments (a//b, a leading /) handled?

What a strong answer covers

  • Parses the path into major parts, each a list of minor parts, and writes one compress(word) with the short-word rule agreed.
  • Part 2: when a major part has more than m minor parts, compresses the first m - 1 and merges the rest into one word, compressed from the original letters, not from tokens already compressed.
  • Part 3: gives every major part one token, then hands out the remaining t - majors tokens from left to right, each part taking at most what it can use, and applies part 2 with each part's budget.
  • Edge cases: m = 1, t equal to the number of major parts, words of one or two letters.
  • Tests worked out by hand for each part.

Follow-ups

  • Decode a compressed path given a dictionary of known words.
  • Spread the token budget to keep the output shortest, not left to right.
  • Non-ASCII words.

Where it's asked

  • Stripe · Onsite coding: debug, integrate, build · Last asked Nov 202360 min · Project editor with starter code and tests: fix bugs in an unfamiliar codebase, wire an external API spec into a service, or complete a skeleton in parts · Varies by session: some onsites have one AI-assisted session and an integration session without AI

What it tests

strings · greedy

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