Skip to main content

Find time from time ranges (including overlapping ranges)

 This is a very simple problem. In this trying to find a given time from ranges of times. So, I have a collection which stores different time ranges (including overlapping time ranges). The job is to find or search if a time provided by user exists in time ranges collection.

Example: Let's assume I have following collections of time ranges:

1. 07:00 - 09:00 
2. 13:45 - 15:15
3. 16:25 - 18:10
4. 08:30 - 10:00

Now, need to find if time 09:30 is present in that collection or not. If it finds it shall print true, otherwise false. Similarly it can be use to check other times too.

Solution: To store time ranges, what I did is converted start and end time to decimal numbers respectively and stored them in STL's set (multiset) used to address overlapping ranges. As we know that set data structure in STL is a tree (Red Black Tree / Balanced Binary tree). 

Time Complexity: 
1. set::insert - If N elements are inserted, Nlog(size+N). Implementations may optimize if the range is already sorted. (Reference: set::insert)
2. set::find - Logarithmic in size (size of the set). (Reference: set::find)

The set templates signature in STL is like below:
template < class T,                        // set::key_type/value_type
           class Compare = less<T>,        // set::key_compare/value_compare
           class Alloc = allocator<T>      // set::allocator_type
           > class set;

It has a template argument key_compare. So, we need to provide a compare function which will do comparison with respect to ranges and sort (using strict weak ordering) while storing ranges as well as help us to find if a time is part of any range(s) stored in the set.

To solve this I have followed a structure like header only library and used it in main.cpp. A namespace config has been used to control if seconds need to be processed to generate decimal or not. To do so used inline global variable in config namespace which helped to decouple configuration from API to find date in ranges.

Solution Code:
 // mylib.h
#ifndef MYLIB
#define MYLIB

#include <iostream>
#include <iomanip>
#include <set>
#include <sstream>
#include <string>

using std::tm;
using std::istringstream;
using std::string;
using std::multiset;
using std::pair;

namespace my_lib
namespace config
inline bool compute_seconds = false;

typedef pair<double, double> timeranges;
struct timeRangeCompare
bool operator()(const timeranges& lvalue, const timeranges& rvalue) const
return lvalue.second < rvalue.first;

bool isInRange(const multiset<timeranges, timeRangeCompare>& iRanges, 
                double value)
return iRanges.find(timeranges(value, value)) != iRanges.end();

double convert_StringTime(string& s)
std::tm tm;
istringstream ss(s);
double fNumber = 0.;

if (!config::compute_seconds)
ss >> std::get_time(&tm, "%H:%M");
fNumber = tm.tm_hour + (tm.tm_min / 60.0);
ss >> std::get_time(&tm, "%T");
fNumber = tm.tm_hour + (tm.tm_min / 60.0) + (tm.tm_sec / 3600.0);
                        /* The construct (tm.tm_min / 60.0) may results in warning 
                       'The left operand of '/' is a garbage value' by clang-tidy tool. 
                        In that case we can replace "%T" format to "%H:%M:%S"*/
return fNumber;


// main.cpp
#include "mylib.h"

using std::cout;
using std::string;
using std::boolalpha;

int main()
    // This part deals with time ranges including overlapping
    multiset<my_lib::timeranges, my_lib::timeRangeCompare> rangesObj;

    // Time range: 1
    string sStartTime{"10:15"};
    string sEndTime{ "12:15" };
    double fStartTime = my_lib::convert_StringTime(sStartTime);
    double fEndTime = my_lib::convert_StringTime(sEndTime);
    rangesObj.insert(my_lib::timeranges(fStartTime, fEndTime));

    // Time range: 2
    sStartTime = "14:30";
    sEndTime = "15:15";
    fStartTime = my_lib::convert_StringTime(sStartTime);
    fEndTime = my_lib::convert_StringTime(sEndTime);
    rangesObj.insert(my_lib::timeranges(fStartTime, fEndTime));

    // Time range: 3. 
    // This is overlapping range with Time range 1(above)
    my_lib::config::compute_seconds = true; // Now seconds will be used to compute number

    sStartTime = "11:30:45";
    sEndTime = "12:40:23";
    fStartTime = my_lib::convert_StringTime(sStartTime);
    fEndTime = my_lib::convert_StringTime(sEndTime);
    rangesObj.insert(my_lib::timeranges(fStartTime, fEndTime));

    // Now check a time if it's within a range 
    // Should display true as it's already in range
    string sTimeToCheck{ "12:10:00" };
    double dToCheck = my_lib::convert_StringTime(sTimeToCheck);
    cout << boolalpha << my_lib::isInRange(rangesObj, dToCheck) << "\n";

    // This one isn't in time slots hence must return false;
    sTimeToCheck = "16:30:00";
    dToCheck = my_lib::convert_StringTime(sTimeToCheck);
    cout << boolalpha << my_lib::isInRange(rangesObj, dToCheck) << "\n";

    return 0;

*** VS-2019 is used with flag set to /std:c++17.


Popular posts from this blog

Variadic template class to add numbers recursively during compilation

 The idea of having a class to add numbers (variable parameters) during compilation time recursively. Also wanted to restrict types to a single type while sending parameters to class member function. That said, if we mix int, float and double types to add function shall result in compilation error. How do we achieve this. The below is the code which actually helps to achieve this: <code> #include < fmt/format.h > template < typename T> class MyVarSumClass{     private :         T _sum = 0 ;     public :         template < typename ... TRest>         T add(T num, TRest... nums){             static_assert (std::conjunction<std::is_same<TRest, T>...>{}); /* Assert fails                if types are different */             _sum += num;             return add(nums...); // Next parameter packs gets picked recursively         }         // Base case         T add(T num){             _sum += num;             return _sum;         } }; int main() {     My

A simple approach to generate Fibonacci series via multi-threading

T his is a very simple approach taken to generate the Fibonacci series through multithreading. Here instead of a function, used a function object. The code is very simple and self-explanatory.  #include <iostream> #include <mutex> #include <thread> class Fib { public:     Fib() : _num0(1), _num1(1) {}     unsigned long operator()(); private:     unsigned long _num0, _num1;     std::mutex mu; }; unsigned long Fib::operator()() {     mu.lock(); // critical section, exclusive access to the below code by locking the mutex     unsigned long  temp = _num0;     _num0 = _num1;     _num1 = temp + _num0;     mu.unlock();     return temp; } int main() {     Fib f;          int i = 0;     unsigned long res = 0, res2= 0, res3 = 0;     std::cout << "Fibonacci series: ";     while (i <= 15) {         std::thread t1([&] { res = f(); }); // Capturing result to respective variable via lambda         std::thread t2([&] { res2 = f(); });         std::thread t3(

A concept to a product (Kimidori [ 黄緑]) - Part 2

In the previous part , we have seen KIMIDORI [ 黄緑] detect if a URL is malicious. In this part, we will see the details that KIMIDORI [ 黄緑] fetches out of the URL provided. As an example, provided a safe URL,, and let's see what it brings out: As we can see, the link is safe and the link is active, which means we can just click on the link to open it on IE.  Now it's time to look into the URL report (still under development):  We have URLs IP, Location, and HTTP Status code. The Report part is a sliding window, the Show Report button shows as well as hides the report. Show / Hide Report is a toggle button. Let's see if we get the same details for any bad (phishing / malicious) URL: Took an URL example from a phishing link and tested it. The tool detected it as not a good link (Screen Shot Below) & link does not activate unlike a safe URL: Now let's see the report part for more details including domain registration details: It looks like it&