#2424

Longest Uploaded Prefix

Medium
Hash TableBinary SearchUnion-FindDesignBinary Indexed TreeSegment TreeHeap (Priority Queue)Ordered SetHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses an array to track uploaded videos and a pointer to track the longest prefix. This allows us to efficiently check the longest prefix after each upload without re-checking all previous uploads.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an array to keep track of uploaded videos and a pointer for the longest prefix.
  2. 2Step 2: When uploading a video, mark it as uploaded.
  3. 3Step 3: Increment the pointer while the next video in sequence is uploaded.
solution.py12 lines
1class LUPrefix:
2    def __init__(self, n: int):
3        self.uploaded = [False] * (n + 1)
4        self.longest_prefix = 0
5
6    def upload(self, video: int) -> None:
7        self.uploaded[video] = True
8        while self.longest_prefix + 1 < len(self.uploaded) and self.uploaded[self.longest_prefix + 1]:
9            self.longest_prefix += 1
10
11    def longest(self) -> int:
12        return self.longest_prefix

Complexity note: The time complexity is O(n) because each upload can potentially increment the longest prefix pointer only once, and we only traverse the uploaded array once per upload.

  • 1Tracking the longest prefix efficiently can save time and avoid unnecessary checks.
  • 2Using an array to mark uploaded videos allows constant time checks for the longest prefix.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.