Algorithm


Problem Name: 352. Data Stream as Disjoint Intervals

Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals.

Implement the SummaryRanges class:

  • SummaryRanges() Initializes the object with an empty stream.
  • void addNum(int value) Adds the integer value to the stream.
  • int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi]. The answer should be sorted by starti.

 

Example 1:

Input
["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"]
[[], [1], [], [3], [], [7], [], [2], [], [6], []]
Output
[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]

Explanation
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1);      // arr = [1]
summaryRanges.getIntervals(); // return [[1, 1]]
summaryRanges.addNum(3);      // arr = [1, 3]
summaryRanges.getIntervals(); // return [[1, 1], [3, 3]]
summaryRanges.addNum(7);      // arr = [1, 3, 7]
summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]
summaryRanges.addNum(2);      // arr = [1, 2, 3, 7]
summaryRanges.getIntervals(); // return [[1, 3], [7, 7]]
summaryRanges.addNum(6);      // arr = [1, 2, 3, 6, 7]
summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]

 

Constraints:

  • 0 <= value <= 104
  • At most 3 * 104 calls will be made to addNum and getIntervals.

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


var SummaryRanges = function() {
  this.intervals = []
}

SummaryRanges.prototype.addNum = function(val) {
  const current = [val, val]
  const intervals = this.intervals
  const less = []
  const more = []
  for (let vals of intervals) {
    if (vals[0] > current[1] + 1) {
      more.push(vals)
    } else if (vals[1] + 1 < current[0]) {
      less.push(vals)
    } else {
      current[0] = Math.min(current[0], vals[0])
      current[1] = Math.max(current[1], vals[1])
    }
  }
  this.intervals = [...less, current, ...more]
}

SummaryRanges.prototype.getIntervals = function() {
  return this.intervals
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"] [[], [1], [], [3], [], [7], [], [2], [], [6], []]

#2 Code Example with Python Programming

Code - Python Programming


class SummaryRanges:

    def __init__(self):
        self.starts, self.ends, self.used = [-float("inf"), float("inf")], [-float("inf"), float("inf")], set()
        
    def addNum(self, val):
        if val not in self.used:
            self.used.add(val)
            i = bisect.bisect_left(self.starts, val) - 1
            if self.ends[i] + 1 == val and val + 1 == self.starts[i + 1]: # if val is the gap btw 2 intervals
                del self.starts[i + 1]
                del self.ends[i]
            elif self.ends[i] + 1 == val: #if val is adjacent to current end
                self.ends[i] += 1
            elif self.starts[i + 1] == val + 1: # if val is adjacent to next start
                self.starts[i + 1] -= 1
            elif val > self.ends[i]: # if val is independent of those 2 intervals
                self.starts.insert(i + 1, val) 
                self.ends.insert(i + 1, val)
            
    def getIntervals(self):
Copy The Code & Try With Live Editor

Input

x
+
cmd
["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"] [[], [1], [], [3], [], [7], [], [2], [], [6], []]

Output

x
+
cmd
[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]

#3 Code Example with C# Programming

Code - C# Programming


using System;
using System.Collections.Generic;
using System.Linq;

namespace LeetCode
{
    public class _0352_DataStreamAsDisjointIntervals
    {
        private readonly SortedDictionary < int, int[]> map;

        /** Initialize your data structure here. */
        public _0352_DataStreamAsDisjointIntervals()
        {
            map = new SortedDictionary<int, int[]>();
        }

        public void AddNum(int val)
        {
            if (map.ContainsKey(val)) return;

            var keys = map.Keys.ToArray();
            var indexHi = Array.BinarySearch(keys, val);
            indexHi = ~indexHi;
            var indexLo = indexHi - 1;
            if (indexLo >= 0 && indexLo  <  keys.Length && indexHi < keys.Length && map[keys[indexLo]][1] + 1 == val && keys[indexHi] == val + 1)
            {
                map[keys[indexLo]][1] = map[keys[indexHi]][1];
                map.Remove(keys[indexHi]);
            }
            else if (indexLo >= 0 && indexLo  <  keys.Length && map[keys[indexLo]][1] + 1 >= val)
                map[keys[indexLo]][1] = Math.Max(map[keys[indexLo]][1], val);
            else if (indexHi < keys.Length && keys[indexHi] == val + 1)
            {
                map[val] = new int[] { val, map[keys[indexHi]][1] };
                map.Remove(keys[indexHi]);
            }
            else
                map[val] = new int[] { val, val };
        }

        public int[][] GetIntervals()
        {
            return map.Values.ToArray();
        }
    }

}
Copy The Code & Try With Live Editor

Input

x
+
cmd
["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"] [[], [1], [], [3], [], [7], [], [2], [], [6], []]

Output

x
+
cmd
[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]
Advertisements

Demonstration


Previous
#350 Leetcode Intersection of Two Arrays II Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#354 Leetcode Russian Doll Envelopes Solution in C, C++, Java, JavaScript, Python, C# Leetcode