Tutorialspoint
Problem
Solution
Submissions

URL Shortener Service with Analytics

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 15

Write a Python program to implement a URL shortener service with analytics tracking capabilities. The service should be able to convert long URLs into short identifiers, redirect users, and track access statistics.

Example 1
  • Input:
    shortener = URLShortener()
    short_url = shortener.shorten("https://www.example.com/very/long/path/to/resource?param1=value1¶m2=value2")
    print(short_url)
    original_url = shortener.redirect(short_url)
    print(original_url)
  • Output:
    abc123
    https://www.example.com/very/long/path/to/resource?param1=value1¶m2=value2
  • Explanation:
    • Generate short identifier "abc123".
    • Redirect retrieves and returns original long URL.
Example 2
  • Input:
    shortener = URLShortener()
    short_url1 = shortener.shorten("https://www.example.com/page1")
    short_url2 = shortener.shorten("https://www.example.com/page2")
    shortener.redirect(short_url1)
    shortener.redirect(short_url1)
    shortener.redirect(short_url2)
    analytics = shortener.get_analytics(short_url1)
    print(analytics)
  • Output:
    {'url': 'https://www.example.com/page1', 'visits': 2, 'last_accessed': '2025-04-09 15:30:45'}
  • Explanation:
    • Tracks visit counts and timestamps.
    • Returns analytics for shortened URLs.
Constraints
  • Max URL length: 2048 characters
  • Short URL length: 6-8 characters
  • Handles ≥ 1,000,000 URLs
  • Time Complexity: O(1)
  • Space Complexity: O(n)
Hash MapMapEYSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a hash function or counter to generate unique short codes
  • Store the mapping between short codes and original URLs in a dictionary/hash map
  • Implement tracking of access counts and timestamps for analytics
  • Consider using a consistent hash algorithm for generating short codes
  • Add validation to ensure input URLs are properly formatted

Steps to solve by this approach:

 Step 1: Initialize the URLShortener class with dictionaries to store URL mappings and analytics data.
 Step 2: Implement a method to generate random short codes of fixed length.
 Step 3: Create a shorten method that validates URLs, checks for duplicates, and generates a unique short code.
 Step 4: Implement a redirect method that updates analytics and returns the original URL.
 Step 5: Add a get_analytics method to retrieve visit data for a specific short URL.

Submitted Code :