Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Home
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets

Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Back to Problems

535. Encode and Decode TinyURL

Medium86.5% Acceptance
Hash TableStringDesign
Asked by:
M
Microsoft
ProblemSolutions (4)VideosCompanies (3)Notes

Problem Statement

Note: This is a companion problem to the System Design problem: Design TinyURL.

TinyURL 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. Design a class to encode a URL and decode a tiny URL.

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.

Implement the Solution class:

  • Solution() Initializes the object of the system.
  • String encode(String longUrl) Returns a tiny URL for the given longUrl.
  • String decode(String shortUrl) Returns the original long URL for the given shortUrl. It is guaranteed that the given shortUrl was encoded by the same object.

Example 1:

Input: url = "https://leetcode.com/problems/design-tinyurl"
Output: "https://leetcode.com/problems/design-tinyurl"

Explanation:
Solution obj = new Solution();
string tiny = obj.encode(url); // returns the encoded tiny url.
string ans = obj.decode(tiny); // returns the original url after decoding it.

Constraints:

  • 1 <= url.length <= 104
  • url is guranteed to be a valid URL.
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
A
Amazon
B
Bloomberg

Approach

The core idea behind #535 Encode and Decode TinyURL is to design a system that converts a long URL into a short one and later retrieves the original URL. A common approach is to use a Hash Table to store the mapping between the generated short key and the original long URL.

During encoding, generate a unique identifier (such as an incremental ID or a random string) and transform it into a compact form using techniques like Base62 encoding. This identifier becomes the suffix of the TinyURL. Store the mapping shortKey → longURL in a hash map so it can be retrieved later.

During decoding, extract the key from the short URL and look it up in the hash table to return the stored original URL. Since hash map lookups are constant time on average, both operations remain efficient.

This design ensures fast lookups and minimal collisions while keeping the short URLs compact and unique.

Complexity

OperationTime ComplexitySpace Complexity
Encode URLO(1) averageO(n) for storing mappings
Decode URLO(1) averageO(n)

Video Solution Available

NeetCode

View all video solutions

Solutions (4)

Hash Map Approach

This approach utilizes a hash map (dictionary) where each long URL is stored along with a unique identifier that serves as the short URL.
This method involves two main operations:

  • Encoding: Generate a unique short URL for each long URL using a sequential counter. Store the mapping in the hash map.
  • Decoding: Retrieve the original URL using the short URL by referencing the hash map.

Time Complexity: O(1) for both encode and decode operations.
Space Complexity: O(n), where n is the number of URLs encoded.

PythonJavaScript
1import random
2import string
3
4class Solution:
5
6    def __init__(self):
7        self.url_map = {}
8        self.code_map = {}
9        self.chars = string.ascii_letters + string.digits
10
11    def encode(self, longUrl: str) -> str:
12        """
13        Encodes a URL to a shortened URL.
14        """
15        code = ''.join(random.choice(self.chars) for _ in range(6))
16        while code in self.code_map:
17            code = ''.join(random.choice(self.chars) for _ in range(6))
18        self.url_map[code] = longUrl
19        self.code_map[longUrl] = code
20        return "http://tinyurl.com/" + code
21
22    def decode(self, shortUrl: str) -> str:
23        """
24        Decodes a shortened URL to its original URL.
25        """
26        code = shortUrl.split("/")[-1]
27        return self.url_map.get(code, "")

Explanation

The encode method generates a 6-character random string for each long URL, stores this mapping in a dictionary, and returns the short URL. The decode method retrieves the original URL using the short URL by referencing the stored dictionary entries. Random generation ensures low collision chances.

Base Conversion Approach

This approach converts a unique identifier into a base62 string, which is used as the short URL.
Using this method involves several steps:

  • Encoding: Maintain a counter that increments with each URL encoding. Convert this counter using base62 encoding to derive the short URL.
  • Decoding: Use the base62 string to retrieve the original counter and access the mapped long URL.

Time Complexity: O(log n) for encoding as base conversion takes logn operations. O(1) for decoding.
Space Complexity: O(n), for storing the mappings.

PythonJava
1class Solution:
2
3


Video Solutions

Watch expert explanations and walkthroughs

Encode and Decode TinyURL - Leetcode 535 - Python

NeetCode
9:0220,685 views

Asked By Companies

3 companies
M
Microsoft
A
Amazon
B
Bloomberg

Prepare for Interviews

Practice problems asked by these companies to ace your technical interviews.

Explore More Problems

Notes

Personal Notes

Jot down your thoughts, approach, and key learnings

0 characters

Similar Problems

Longest Substring Without Repeating CharactersMedium
Integer to RomanMedium
Roman to IntegerEasy
Letter Combinations of a Phone NumberMedium
More similar problems

Related Topics

Hash TableStringDesignHash Function

Problem Stats

Acceptance Rate86.5%
DifficultyMedium
Companies3

Practice on LeetCode

Solve with full IDE support and test cases

Solve Now

Frequently Asked Questions

Is Encode and Decode TinyURL asked in FAANG interviews?

Yes, this problem is a common system design and design-oriented coding question in technical interviews, including FAANG-style interviews. It tests understanding of hashing, data storage, and scalable URL shortening strategies.

How are short URLs typically generated in TinyURL systems?

Short URLs are commonly generated using incremental IDs converted to Base62 or by generating random alphanumeric strings. These methods help keep the URL compact while ensuring uniqueness and scalability.

What data structure is best for Encode and Decode TinyURL?

A hash table is the most suitable data structure because it allows constant-time insertion and lookup. This ensures that both encoding and decoding operations remain efficient even as the number of stored URLs grows.

What is the optimal approach for Encode and Decode TinyURL?

The optimal approach uses a hash map to store mappings between a generated short key and the original long URL. A unique ID or random string is created during encoding, and decoding simply retrieves the original URL using a hash lookup.

def
__init__
(
self
)
:
4
self
.
url_map
=
{
}
5
self
.
counter
=
0
6
self
.
chars
=
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
7
8
def
_to_base62
(
self
,
num
:
int
)
-
>
str
:
9
base
=
62
10
res
=
[
]
11
while
num
:
12
num
,
rem
=
divmod
(
num
,
base
)
13
res
.
append
(
self
.
chars
[
rem
]
)
14
return
''
.
join
(
reversed
(
res
)
)
15
16
def
encode
(
self
,
longUrl
:
str
)
-
>
str
:
17
"""
18 Encodes a URL to a shortened URL.
19
"""
20
self
.
counter
+=
1
21
code
=
self
.
_to_base62
(
self
.
counter
)
22
self
.
url_map
[
code
]
=
longUrl
23
return
"http://tinyurl.com/"
+
code
24
25
def
decode
(
self
,
shortUrl
:
str
)
-
>
str
:
26
"""
27 Decodes a shortened URL to its original URL.
28
"""
29
code
=
shortUrl
.
split
(
"/"
)
[
-
1
]
30
return
self
.
url_map
.
get
(
code
,
""
)

Explanation

This Python implementation utilizes a counter incremented on each URL encoding, converting it to a base62 string as the short URL. The original URL is fetched using this unique code during decoding.