LeetCode 729: My Calendar I Solution

Master LeetCode problem 729 (My Calendar I), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To solve this problem, we can use a data structure to store the booked events. One common approach is to use a TreeMap in Java, a map in C++, and a dictionary in Python. We can store the booked events in the data structure, where the key represents the start time of the event and the value represents the end time of the event.

When trying to book a new event, we iterate through the existing booked events to check for any overlap. If there is no overlap, we add the new event to the data structure and return true. If there is an overlap, we return false.

Time Complexity: O(log N) on average for each booking operation, where N is the number of booked events. Space Complexity: O(N) to store the booked events.

Solution Code

class MyCalendar {
    TreeMap<Integer, Integer> calendar;

    public MyCalendar() {
        calendar = new TreeMap<>();
    }

    public boolean book(int start, int end) {
        Integer prev = calendar.floorKey(start);
        Integer next = calendar.ceilingKey(start);

        if ((prev == null || calendar.get(prev) <= start) && (next == null || end <= next)) {
            calendar.put(start, end);
            return true;
        }
        return false;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 729 (My Calendar I)?

This page provides optimized solutions for LeetCode problem 729 (My Calendar I) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 729 (My Calendar I)?

The time complexity for LeetCode 729 (My Calendar I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 729 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 729 in Java, C++, or Python.

Back to LeetCode Solutions