Data Stream as Disjoint Intervals in C++


Suppose we have a data stream input of integers, these are like a1, a2, ..., an, ..., we have to summarize the numbers seen so far as a list of disjoint intervals. For example, suppose the input integers are 1, 3, 8, 2, 7, ..., then the summary will be −

  • [1,1]

  • [1, 1], [3, 3]

  • [1, 1], [3, 3], [8, 8]

  • [1, 3], [8, 8]

  • [1, 3], [7, 8].

To solve this, we will follow these steps −

  • Make a set called nums

  • in the initializer, set low := -inf and high := inf

  • From the addNum method that takes num as input, insert num into the set nums

  • From the get interval method, do following −

  • Define one 2D array ret

  • it := start element of set nums

  • while it is in the set, do −

    • x := value of it

    • if ret is empty or element at index 1 of last element of ret + 1 < x, then,

      • insert pair { x, x } at the end of ret

    • Otherwise

      • increase the element present at index 1 of last element of ret by 1

    • it to next element

  • return ret

Example

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h<
using namespace std;
void print_vector(vector<vector<auto> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class SummaryRanges {
   public:
   set <int> nums;
   int low, high;
   SummaryRanges() {
      low = INT_MAX;
      high = INT_MIN;
   }
   void addNum(int val) {
      nums.insert(val);
   }
   vector<vector<int>> getIntervals() {
      vector < vector <int> > ret;
      set <int> :: iterator it = nums.begin();
      while(it != nums.end()){
         int x = *it;
         if(ret.empty() || ret.back()[1] + 1 < x){
            ret.push_back({x, x});
         } else {
            ret.back()[1]++;
         }
         it++;
      }
      return ret;
   }
};
main(){
   SummaryRanges ob;
   ob.addNum(1);
   print_vector(ob.getIntervals());
   ob.addNum(3);
   print_vector(ob.getIntervals());
   ob.addNum(8);
   print_vector(ob.getIntervals());
   ob.addNum(2);
   print_vector(ob.getIntervals());
   ob.addNum(7);
   print_vector(ob.getIntervals());
}

Input

Initialize the class, then insert one element at a time and see the intervals. So the elements are [1,3,8,2,7]

Output

[[1, 1, ],]
[[1, 1, ],[3, 3, ],]
[[1, 1, ],[3, 3, ],[8, 8, ],]
[[1, 3, ],[8, 8, ],]
[[1, 3, ],[7, 8, ],]

Updated on: 27-May-2020

132 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements