category-wise-problems

contains category wise problems(data structures, competitive) of popular platforms.

View the Project on GitHub mayankdutta/category-wise-problems

729. My Calendar I

Brute

class MyCalendar {
public:
    vector<pair<int, int>> arr;
    MyCalendar() { }

    bool book(int start, int end) {
        for (const auto& [s, e]: arr) {
            if (max(s, start) < min(e, end)) {
                return false;
            }
        }
        arr.push_back({start, end});
        return true;
    }
};

Optimized

class MyCalendar {
    public:
    set<pair<int, int>> st;
    MyCalendar() { }

    bool book(int start, int end) {
        if (st.empty()) {
            st.insert({start, end});
            return true;
        }

        auto it = st.lower_bound({start, end});
        if (it == st.end()) {
            -- it;
            if (it->second <= start) {
                st.insert({start, end});
                return true;
            }
        } else if (it == st.begin()) {
            if (end <= it->first) {
                st.insert({start, end});
                return true;
            }
        } else {
            auto prev = it;
            --prev;
            if (prev->second <= start && end <= it->first) {
                st.insert({start, end});
                return true;
            }
        }
        return false;
    }
};