← Home

535. Encode and Decode TinyURL

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
535

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 535. Encode and Decode TinyURL, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are encode, decode.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Note: This is a companion problem to the System Design problem: Design TinyURL.
03TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.
04
05Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
06**/
07
08//adopted from https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/
09//Your runtime beats 99.35 % of cpp submissions.
10class Solution {
11public:
12    map<string, int> longUrl2id;
13    map<int, string> id2longUrl;
14        
15    // Encodes a URL to a shortened URL.
16    string encode(string longUrl) {
17        // Map to store 62 possible characters
18        char map[] = "abcdefghijklmnopqrstuvwxyzABCDEF"
19                     "GHIJKLMNOPQRSTUVWXYZ0123456789";
20        
21        string shorturl;
22        int n;
23        
24        if(longUrl2id.find(longUrl)==longUrl2id.end()){
25            n = longUrl2id.size();
26            longUrl2id.insert(pair<string, int>(longUrl, n));
27            id2longUrl.insert(pair<int, string>(n, longUrl));
28        }else{
29            n = longUrl2id[longUrl];
30        }
31
32        // Convert given integer id to a base 62 number
33        while (n)
34        {
35            shorturl.push_back(map[n%62]);
36            n = n/62;
37        }
38
39        // Reverse shortURL to complete base conversion
40        reverse(shorturl.begin(), shorturl.end());
41
42        return shorturl;
43    }
44
45    // Decodes a shortened URL to its original URL.
46    string decode(string shortUrl) {
47        int id = 0; // initialize result
48  
49        // A simple base conversion logic
50        for (int i=0; i < shortUrl.length(); i++)
51        {
52            if ('a' <= shortUrl[i] && shortUrl[i] <= 'z')
53              id = id*62 + shortUrl[i] - 'a';
54            if ('A' <= shortUrl[i] && shortUrl[i] <= 'Z')
55              id = id*62 + shortUrl[i] - 'A' + 26;
56            if ('0' <= shortUrl[i] && shortUrl[i] <= '9')
57              id = id*62 + shortUrl[i] - '0' + 52;
58        }
59        return id2longUrl[id];
60    }
61};
62
63// Your Solution object will be instantiated and called as such:
64// Solution solution;
65// solution.decode(solution.encode(url));

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.