#352

Data Stream as Disjoint Intervals

Hard
Hash TableBinary SearchUnion-FindDesignData StreamOrdered 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 a data structure that allows for efficient insertion and interval merging. By using a sorted set, we can quickly find where to insert new numbers and merge intervals as necessary.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a sorted data structure (like a TreeSet or SortedSet) to store the numbers.
  2. 2Step 2: When adding a number, check adjacent numbers to see if it merges with existing intervals.
  3. 3Step 3: Create intervals based on the merged ranges and return them.
solution.py37 lines
1class SummaryRanges:
2    def __init__(self):
3        self.intervals = []
4
5    def addNum(self, value: int) -> None:
6        if not self.intervals:
7            self.intervals.append([value, value])
8            return
9        for i in range(len(self.intervals)):
10            start, end = self.intervals[i]
11            if value < start:
12                self.intervals.insert(i, [value, value])
13                break
14            elif start <= value <= end:
15                return
16            elif value == end + 1:
17                self.intervals[i][1] = value
18                if i + 1 < len(self.intervals) and self.intervals[i + 1][0] == value + 1:
19                    self.intervals[i][1] = self.intervals[i + 1][1]
20                    self.intervals.pop(i + 1)
21                return
22            elif value == start - 1:
23                self.intervals[i][0] = value
24                return
25            elif value > end:
26                if i + 1 < len(self.intervals) and self.intervals[i + 1][0] == value + 1:
27                    self.intervals[i][1] = self.intervals[i + 1][1]
28                    self.intervals.pop(i + 1)
29                elif i + 1 == len(self.intervals):
30                    self.intervals.append([value, value])
31                else:
32                    continue
33        else:
34            self.intervals.append([value, value])
35
36    def getIntervals(self) -> List[List[int]]:
37        return self.intervals

Complexity note: The time complexity is O(n) because we only iterate through the set of numbers once to create intervals, and the space complexity is O(n) due to storing the intervals.

  • 1Using a sorted data structure helps maintain order and allows for efficient merging of intervals.
  • 2Handling edge cases like duplicates and adjacent numbers is crucial.

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