Longest Uploaded Prefix — LeetCode 2424 Python Solution

MediumUnion FindDesignBinary Indexed TreeSegment TreeHash TableBinary SearchOrdered SetHeap (Priority Queue)
Problem
#2424
Pattern
Union-Find
Reading time
4 min

The problem

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.

Example

Input
["LUPrefix", "upload", "longest", "upload", "longest", "upload", "longest"]
Output
[null, null, 0, null, 1, null, 3]
Explanation
LUPrefix server = new LUPrefix(4); // Initialize a stream of 4 videos.

Python solution

Python
class LUPrefix:
    def __init__(self, n: int):
        self.r = 0
        self.s = set()

    def upload(self, video: int) -> None:
        self.s.add(video)
        while self.r + 1 in self.s:
            self.r += 1

    def longest(self) -> int:
        return self.r


# Your LUPrefix object will be instantiated and called as such:
# obj = LUPrefix(n)
# obj.upload(video)
# param_2 = obj.longest()

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Union-Find

Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 2424. Longest Uploaded Prefix is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.

The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2424. Longest Uploaded Prefix?
LeetCode 2424. Longest Uploaded Prefix is rated Medium on LeetCode.
What is the time complexity of LeetCode 2424. Longest Uploaded Prefix?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2424. Longest Uploaded Prefix?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2424. Longest Uploaded Prefix cover?
LeetCode 2424. Longest Uploaded Prefix is tagged Union Find, Design, Binary Indexed Tree, Segment Tree, Hash Table, Binary Search, Ordered Set and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview