Problem Description
You are given a stream of n videos, each represented by a distinct number from 1 to n. These videos are uploaded in an arbitrary order. At any point in time, you need to determine the longest prefix (i.e., the maximum value i) for which all videos in the range [1, i] have been uploaded.
Key Insights
- Maintain a pointer (or counter) that represents the smallest video number that has not yet been confirmed as part of the prefix.
- Use a boolean array (or a hash set) to track which videos have been uploaded.
- After each upload, check if the uploaded video allows the pointer to move forward, thereby extending the prefix.
- Since each video is uploaded exactly once, the operations are efficient and only require an amortized constant time per call.
Space and Time Complexity
Time Complexity: O(1) amortized per operation (upload and longest) Space Complexity: O(n) for storing the uploaded status of each video
Solution
To solve the problem, we use an array (or similar data structure) to mark the uploaded videos. We also maintain a pointer, currentPrefix, starting at 1. When a video is uploaded, we mark it as uploaded. Then, we check if the currentPrefix video is uploaded; if it is, we increment the pointer until we reach a video that hasn’t been uploaded. This pointer always indicates the first video missing in the prefix, so the longest uploaded prefix is currentPrefix - 1.