Leetcode 2424: Longest Uploaded Prefix

grid47
grid47
Exploring patterns and algorithms
Mar 9, 2024 5 min read

You are given a stream of n distinct videos, each represented by a unique number from 1 to n. You need to design a data structure that tracks the longest prefix of uploaded videos at any point in time. A prefix is considered uploaded if all videos from 1 to i (inclusive) have been uploaded to the server.
Problem
Approach
Steps
Complexity
Input: The input consists of two types of operations. The first operation initializes the system with n distinct videos. The second operation uploads a specific video to the server. The third operation returns the length of the longest uploaded prefix.
Example: LUPrefix(5); upload(4); longest(); upload(2); longest(); upload(1); longest();
Constraints:
• 1 <= n <= 10^5
• 1 <= video <= n
• All video numbers are distinct.
• At most 2 * 10^5 operations (upload and longest) will be performed.
Output: For each 'longest' operation, return the length of the longest uploaded prefix.
Example: Output: [null, 0, null, 1, null, 3]
Constraints:
• The result should be an integer representing the length of the longest uploaded prefix.
Goal: Track and return the longest sequence of consecutively uploaded videos starting from 1.
Steps:
• 1. Maintain an array or set to track which videos have been uploaded.
• 2. For each 'upload' operation, mark the corresponding video as uploaded.
• 3. After each upload, check how many consecutive videos starting from 1 have been uploaded, and update the longest uploaded prefix.
• 4. For 'longest' operations, simply return the length of the current longest prefix.
Goal: The solution should handle up to 100,000 videos and 200,000 operations efficiently.
Steps:
• Ensure that the operations scale well with large inputs and constraints.
Assumptions:
• All video numbers are distinct and within the range from 1 to n.
Input: LUPrefix(5); upload(4); longest(); upload(2); longest(); upload(1); longest();
Explanation: Initially, no videos are uploaded, so the longest prefix is 0. After uploading video 4, no continuous prefix exists, so longest remains 0. After uploading video 2, the longest prefix is still 0, as video 1 hasn't been uploaded yet. Once video 1 is uploaded, the longest prefix becomes [1], and then with videos 1, 2, and 4 uploaded, the longest prefix becomes [1, 2, 3].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus