python
algorithms
time slots
scheduling
programming

Python - Algorithm find time slots

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Finding available time slots using Python can be an essential tool for scheduling applications, calendaring systems, or any scenario requiring the allocation of resources in a time-dependent manner. In this article, we'll explore how to craft a Python algorithm to find open time slots between scheduled events. We'll delve into technical details, provide examples, and summarize our findings.

Problem Statement

Given a list of existing scheduled events (also known as busy slots), the goal is to identify free time slots that could accommodate a new event. Each event is defined by a start and end time.

Input and Output

  • Input: A list of tuples where each tuple contains the start and end times of existing events, and the boundaries for the day (start and end of the day).
  • Output: A list of tuples, each representing a free time slot.

Assumptions

  • Times are given in a consistent format (e.g., 24-hour format).
  • End time for each event is strictly greater than the start time.
  • There may be overlaps between existing events.

Technical Explanation

Step-by-Step Approach

  1. Sort Events: Begin by sorting the list of events by their start times. This helps in easily tracking overlapping events and ensuring we process time slots chronologically.
  2. Merge Overlapping Events: Traverse through the sorted events and merge any overlapping events. This simplifies the problem by transforming overlapping events into a single continuous busy period.
  3. Identify Free Slots: Once you have a list of non-overlapping events, identify gaps between the end of one event and the start of the next, as these gaps represent free slots.
  4. Edge Case Handling: Check for free time slots at the beginning of the day before the first event starts and after the last event ends, up until the end of the day.

Python Implementation

Below is a simple Python example implementing the described algorithm:

  • Events: (9, 11), (13, 16), (12, 14), (18, 19)
  • Start of Day: 8
  • End of Day: 20
  • (8, 9)
  • (11, 12)
  • (16, 18)
  • (19, 20)

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.