714277. Easy Task

Medium

Easy Task

Summary

This problem involves using a segment tree to efficiently solve an optimization problem. Given a set of intervals, we need to find all possible sub-intervals that do not overlap with each other. This requires implementing a segment tree data structure and utilizing its properties to query the overlap status of any given sub-interval.

Detailed Explanation

The main idea is to use a segment tree to store the intervals in a way that allows us to quickly check if two intervals overlap. We can then use this information to find all non-overlapping sub-intervals.

Here's a step-by-step breakdown of the solution:

  1. First, we create a segment tree with the given intervals. Each node in the tree represents an interval, and the root node represents the entire set of intervals.
  2. For each node, we store the maximum end point of all intervals that fall within that node's range.
  3. To check if two intervals overlap, we start at the root node and recursively traverse down the tree until we find a node whose range spans both intervals. If such a node exists, then the intervals overlap; otherwise, they do not.
  4. To find all non-overlapping sub-intervals, we iterate over each interval in the set and use the segment tree to check if any existing sub-interval overlaps with it. If no overlap is found, we add the new interval to our list of non-overlapping sub-intervals.

Time complexity: O(n log n) for creating the segment tree and O(log n) for querying the overlap status of an interval.

Space complexity: O(n) for storing the intervals in the segment tree.

Optimized Solutions

Java

View on GeeksforGeeks
class SegmentTree {
    int[] tree;
    int n;

    public SegmentTree(int[] arr) {
        n = arr.length;
        tree = new int[4 * n];
        buildTree(arr, 0, n - 1);
    }

    private void buildTree(int[] arr, int start, int end) {
        if (start == end) {
            tree[4 * start] = arr[start];
            return;
        }
        int mid = (start + end) / 2;
        buildTree(arr, start, mid);
        buildTree(arr, mid + 1, end);
        tree[4 * start + 3] = Math.max(tree[4 * start + 3], tree[4 * mid + 1]);
    }

    public boolean query(int left, int right) {
        if (left >= right) return false;
        return tree[4 * left + 3] <= right && tree[4 * right + 1] >= left;
    }
}

public class EasyTask {
    public static List<int[]> findNonOverlappingSubIntervals(int[][] intervals) {
        SegmentTree st = new SegmentTree(new int[intervals.length]);
        List<int[]> result = new ArrayList<>();
        for (int[] interval : intervals) {
            if (!st.query(interval[0], interval[1])) {
                result.add(interval);
            }
        }
        return result;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.