You are given a stream of n videos, each represented by a distinct number from 1 to n that you need to upload to a server. You need to implement a data structure that calculates the length of the longest uploaded prefix at various points in the upload process.

We consider i to be an uploaded prefix if all videos in the range 1 to i (inclusive) have been uploaded to the server. The longest uploaded prefix is the maximum value of i that satisfies this definition.

Implement the LUPrefix class:

  • LUPrefix(int n) Initializes the object for a stream of n videos.
  • void upload(int video) Uploads video to the server.
  • int longest() Returns the length of the longest uploaded prefix defined above.

Input & Output

Example 1 — Basic Operation Sequence
$ Input: operations = [["LUPrefix",4],["upload",3],["longest"],["upload",1],["longest"],["upload",2],["longest"]]
Output: [null,null,0,null,1,null,3]
💡 Note: Initialize with n=4. Upload 3: longest prefix is 0 (video 1 missing). Upload 1: prefix is 1. Upload 2: now videos 1,2,3 are consecutive, so prefix is 3.
Example 2 — Sequential Uploads
$ Input: operations = [["LUPrefix",3],["upload",1],["longest"],["upload",2],["longest"],["upload",3],["longest"]]
Output: [null,null,1,null,2,null,3]
💡 Note: Upload in order 1,2,3. Each upload extends the prefix: 1→1, 2→2, 3→3.
Example 3 — Reverse Order
$ Input: operations = [["LUPrefix",2],["upload",2],["longest"],["upload",1],["longest"]]
Output: [null,null,0,null,2]
💡 Note: Upload 2 first: prefix is 0 (video 1 missing). Upload 1: now both 1,2 are uploaded, prefix becomes 2.

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ video ≤ n
  • All values of video are distinct
  • At most 2 × 105 calls will be made to upload and longest

Visualization

Tap to expand
Longest Uploaded Prefix: Track consecutive uploads from video 1Upload sequence: 3, 1, 2 (out of order)1234After upload(3): prefix = 0 (video 1 missing)1234After upload(1): prefix = 1 (video 1 available)1234After upload(2): prefix = 3
Understanding the Visualization
1
Input
Stream of video uploads (1 to n)
2
Process
Track consecutive uploads from video 1
3
Output
Length of longest consecutive prefix
Key Takeaway
🎯 Key Insight: Only count consecutive videos starting from 1 - maintain current prefix length and extend when gaps are filled
Asked in
Google 25 Amazon 20 Meta 15
12.0K Views
Medium Frequency
~25 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen