00:00

Problem Statement

Input/Output Examples

Visual Explanation

codeToUrl makes decoding O(1), and urlToCode makes repeated encoding of the same URL return the same code instead of using up a new one.

Approaches

Both approaches store the same two maps. They differ in how the short code is chosen.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. The counter version produces short sequential codes; the random version produces 6-character codes, so the two outputs differ by design. The random version uses a fixed seed so that its output is repeatable.

Complexity Analysis

Here N is the number of URLs stored. Both encode and decode are hash-map operations, so they take O(1) time on average; the maps hold every URL once in each direction.

Interview Tips and Recommended Approach

  • Explain base 62. Using digits and both letter cases gives short, URL-safe codes.
  • Discuss predictability. Sequential codes are short but reveal how many links exist and can be enumerated; random codes avoid that.
  • Mention scaling. In a real service, the maps become a database table, and the counter becomes a distributed id generator.
  • Validate on decode. An unknown code should return null or a not-found error rather than throwing.

Recommended Approach: Counter With Base-62 Codes

Why: it guarantees unique, short codes without any collision handling and keeps both operations at O(1). It is also the easiest version to explain before discussing scaling trade-offs.