Contained Interval in C++


Suppose we have a two-dimensional list of intervals where each interval has two values [start, end]. We have to find whether there's an interval which contains another interval.

So, if the input is like [[2,4],[5,11],[5,9],[10,10]], then the output will be true as [5,11] is containing [5,9].

To solve this, we will follow these steps −

  • sort the array v

  • Define one 2D array ret

  • for each interval it in v −

    • if ret is empty, then −

      • insert it at the end of ret

    • otherwise when last element of ret >= it[0], then −

      • return true

    • Otherwise

      • insert it at the end of ret

  • return false

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool static cmp(vector<int> &a, vector<int> &b) {
      return a[1] == b[1] ? a[0] > b[0] : a[1] < b[1];
   }
   bool solve(vector<vector<int>> &v) {
      sort(v.begin(), v.end(), cmp);
      vector<vector<int>> ret;
      for (auto &it : v) {
         if (ret.empty())
         ret.push_back(it);
         else if (ret.back()[0] >= it[0])
         return true;
         else
         ret.push_back(it);
      }
      return false;
   }
};
main() {
   Solution ob;
   vector<vector<int>> v = {{2,4},{5,11},{5,9},{10,10}};
   cout << (ob.solve(v));
}

Input

{{2,4},{5,11},{5,9},{10,10}}

Output

1

Updated on: 02-Sep-2020

311 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements