DSA
    advanced

    Sweep Line Algorithm

    Sweep Line Algorithm

    Process interval events sorted by position. Essential for meeting rooms, skyline problems, and rectangle area calculations. Often combined with TreeMap or sorted list.

    ⏱ O(n log n)
    💾 O(n)
    Ready
    0
    Active Now
    0
    Max Rooms
    Meeting Timeline
    05101520253035M1M2M3++-+--
    Event Queue (sorted)
    +t=0
    +t=5
    -t=10
    +t=15
    -t=20
    -t=30

    Meetings: [0,30], [5,10], [15,20]. Convert to events: start=+1, end=-1. Sort by time.

    50%
    Live Variables
    meetings3
    events6

    Meeting rooms

    Sequence

    Order the sweep that finds how many rooms a set of meetings needs.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    In Meeting Rooms II, what do sweep line events represent?

    The short version

    Imagine a vertical line sweeping across a map from left to right, like a scanner. As it moves, it tracks which intervals it's currently inside. This lets you process all events in sorted order.

    In more depth

    Events in Motion

    Sweep Line converts interval problems into a sequence of point events.

    Standard Pattern:

    1.Create events: (position, type) where type is START (+1) or END (-1)
    2.Sort events by position (handle ties carefully!)
    3.Sweep through, updating running count or active set
    4.Track maximum count or other metric

    Meeting Rooms Example:

    meetings = [[0,30], [5,10], [15,20]]
    events = [(0,+1), (5,+1), (10,-1), (15,+1), (20,-1), (30,-1)]
    sorted events → sweep → max concurrent = 2 rooms

    Key Gotchas:

    Tie-breaking: In many problems, ends should come before starts at same position
    Use TreeMap for tracking heights (Skyline problem)
    Open vs closed intervals affect event ordering

    When to reach for this

    • Count maximum overlapping intervals
    • Find union/intersection of intervals
    • 2D geometry with rectangles
    • Keywords: 'meeting rooms', 'skyline', 'overlapping intervals'

    Interview Questions

    Google
    Facebook
    Amazon
    Google
    Microsoft
    Citadel
    Facebook
    Amazon
    Two Sigma
    Netflix
    Palantir
    Bloomberg

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required