My Calendar II LeetCode Solution

Last updated on February 28th, 2025 at 02:12 pm

Here, we see a My Calendar II LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Breadth-First Search, Depth-First Search, Tree

Companies

LinkedIn

Level of Question

Medium

My Calendar II LeetCode Solution

My Calendar II LeetCode Solution

1. Problem Statement

You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking.

triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).

The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end.

Implement the MyCalendarTwo class:

  • MyCalendarTwo() Initializes the calendar object.
  • boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false and do not add the event to the calendar.

Example 1:
Input: [“MyCalendarTwo”, “book”, “book”, “book”, “book”, “book”, “book”] [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
Output: [null, true, true, true, false, true, true]

Explanation:
MyCalendarTwo myCalendarTwo = new MyCalendarTwo();
myCalendarTwo.book(10, 20); // return True, The event can be booked.
myCalendarTwo.book(50, 60); // return True, The event can be booked.
myCalendarTwo.book(10, 40); // return True, The event can be double booked.
myCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.
myCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.
myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.

2. Coding Pattern Used in Solution

The coding pattern used in all the provided implementations is “Sweep Line Algorithm”. This pattern is commonly used in interval problems where events are processed in a sorted order (start and end times) to determine overlaps or conflicts. The idea is to increment a counter when an interval starts and decrement it when it ends, keeping track of the maximum overlap at any point.

3. Code Implementation in Different Languages

3.1 My Calendar II C++

class MyCalendarTwo {
public:
    map<int, int> m;
    MyCalendarTwo() {  
    }
    bool book(int start, int end) {
        int sum = 0;
        m[start]++;
        m[end]--;
        map<int,int>::iterator i;
        for (i=m.begin();i != m.end();i++) {
            sum = sum + i->second;
            if (sum >= 3) {
                m[start]--;
                m[end]++;
                return false;
            }
        } 
        return true;        
    }
};

3.2 My Calendar II Java

class MyCalendarTwo {
    Map<Integer, Integer> map;
    public MyCalendarTwo() {
        map = new TreeMap();
    }
    public boolean book(int start, int end) {
        map.put(start, map.getOrDefault(start, 0)+1);
        map.put(end, map.getOrDefault(end, 0)-1);
        int sum=0;
        for(int val : map.values()){
            sum += val;
            if(sum >= 3){
                map.put(start, map.get(start)-1);
                map.put(end, map.get(end)+1);
                if(map.get(start) == 0)
                    map.remove(start);
                return false;
            }
        }
        return true;
    }
}

3.3 My Calendar II JavaScript

var MyCalendarTwo = function() {
  this.calendar = [];
  this.overlaps = [];
};
MyCalendarTwo.prototype.book = function(start, end) {
  for (let date of this.overlaps) {
    if (start < date[1] && end > date[0]) return false;
  }
  for (let date of this.calendar) {
    if (start < date[1] && end > date[0]) {
      this.overlaps.push([Math.max(date[0], start), Math.min(date[1], end)]);
    }
  }
  this.calendar.push([start, end]); 
  return true;
};

3.4 My Calendar II Python

class MyCalendarTwo(object):
    def __init__(self):
        self.lst = []  
    def book(self, start, end):
        self.lst.append((start, +1))
        self.lst.append((end, -1))
        self.lst.sort()
        overlaps = 0
        for book in self.lst:
            overlaps += book[1]
            if overlaps > 2:
                self.lst.remove((start, +1))
                self.lst.remove((end, -1))
                return False
        return True

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n2)O(n)
JavaO(n2)O(n)
JavaScriptO(n2)O(n)
PythonO(n2)O(n)
  • The code uses the Sweep Line Algorithm to handle interval overlaps efficiently.
  • It ensures that no triple bookings are allowed by maintaining a running count of active intervals.
  • While the implementations differ slightly in syntax and data structures, the underlying logic and complexity are consistent across all languages.
Scroll to Top