[Solved] Merge Overlapping Intervals in Python, C/C++ and Java

[Solved] Merge Overlapping Intervals in Python, C/C++ and Java

Problem statement

You have given a list of intervals. Write a program to merge overlapping intervals.

Example

Input:
Given list of intervals: [[1, 3], [2, 6], [8, 10]]

Output:
List of intervals after merging: [[1, 6], [8, 10]]

This coding challenge was asked in Biju’s coding interview.

You can watch the video for a detailed explanation. Else, you can continue with this tutorial.

(Want to learn more coding challenges? Subscribe to the CSEstack YouTube channel.)

Explanation

Here intervals [1, 3] and [2, 6] overlaps. So we can merge these two intervals. The resultant interval after merging is [1, 6].

Interval [8, 10] does not overlap. So it will be as it is.

This coding challenge was asked in Biju’s interview for a software engineering job profile.

Algorithm

  • Sort the intervals by their first value if it is not sorted.
  • Add the first interval in the stack.
  • Traverse all the elements in the given interval array by skipping the first interval. (says i as an index of the interval and arr as interval array)
    • Pop the interval from the stack (says pop_element)
    • Check if the pop_element overlaps with the arr[i] interval.
      (Write the helper function for this. This function will take the two intervals as an input and return True if they overlap. Otherwise, return False.)
    • If overlaps, merge these two intervals and add them to the stack. Else, add arr[i] in the stack.
  • Return output stack as merged intervals.

Let’s write the code for this logic.

For coding practice, I would recommend you write your code. That’s fine whether you write it in C/C++, Java, Python, or any other programming language. You can always refer to the code given below.

Python Program

Prerequisite:

Intervals are represented in the form of a list. In this code, we are going to use various list methods to manipulate the intervals. Check the Python List tutorial.

Here, one of the major steps is to sort the intervals by their first value. In Python, we have the sort() method by which we can sort the intervals by their first value. Python makes the job pretty easy. Isn’t it?

Let’s see the complete program.

Code:

# Helper function to check 
# if the two intervals overlaps
def is_overlaping(a, b):
  if b[0] > a[0] and b[0] < a[1]:
    return True
  else:
    return False


# merge the intervals
def merge(arr):
  #sort the intervals by its first value
  arr.sort(key = lambda x: x[0])

  merged_list= []
  merged_list.append(arr[0])
  for i in range(1, len(arr)):
    pop_element = merged_list.pop()
    if is_overlaping(pop_element, arr[i]):
      new_element = pop_element[0], max(pop_element[1], arr[i][1])
      merged_list.append(new_element)
    else:
      merged_list.append(pop_element)
      merged_list.append(arr[i])
  return merged_list


# test the code
arr = [[1,3], [2,6], [8,10]]
print(merge(arr))

Output:

[[1, 6], [8, 10]]

Java Program

Code:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MergeIntervals {

    // Helper function to check if the two intervals overlap
    public static boolean isOverlapping(int[] a, int[] b) {
        return b[0] > a[0] && b[0] < a[1];
    }

    // Merge the intervals
    public static List<int[]> merge(int[][] intervals) {
        // Sort the intervals by its first value
        Arrays.sort(intervals, Comparator.comparingInt(o -> o[0]));

        List<int[]> mergedList = new ArrayList<>();
        mergedList.add(intervals[0]);

        for (int i = 1; i < intervals.length; i++) {
            int[] popElement = mergedList.remove(mergedList.size() - 1);
            if (isOverlapping(popElement, intervals[i])) {
                int[] newElement = {popElement[0], Math.max(popElement[1], intervals[i][1])};
                mergedList.add(newElement);
            } else {
                mergedList.add(popElement);
                mergedList.add(intervals[i]);
            }
        }

        return mergedList;
    }

    public static void main(String[] args) {
        int[][] arr = {{1, 3}, {2, 6}, {8, 10}};
        List<int[]> mergedIntervals = merge(arr);

        // Print the merged intervals
        for (int[] interval : mergedIntervals) {
            System.out.println("[" + interval[0] + ", " + interval[1] + "]");
        }
    }
}

Output:

[1, 6]
[8, 10]

Explanation:

In the code, I have written three functions. These functions serve the different purposes as below.

  • The isOverlapping function checks if two intervals overlap.
  • The merge function sorts the intervals and then merges overlapping intervals.
  • The main function tests the code with the given example and prints the merged intervals.

C/C++ Program

Code:

#include <stdio.h>
#include <stdlib.h>

// Helper function to check if the two intervals overlap
int is_overlapping(int* a, int* b) {
    return b[0] > a[0] && b[0] < a[1];
}

// Compare function for sorting intervals by their first value
int compare(const void* a, const void* b) {
    return ((int*)a)[0] - ((int*)b)[0];
}

// Merge the intervals
int** merge(int arr[][2], int arrSize, int* returnSize) {
    // Sort the intervals by their first value
    qsort(arr, arrSize, sizeof(arr[0]), compare);

    // Allocate memory for the merged intervals
    int** mergedList = (int**)malloc(arrSize * sizeof(int*));
    for (int i = 0; i < arrSize; ++i) {
        mergedList[i] = (int*)malloc(2 * sizeof(int));
    }

    // Initialize the merged list with the first interval
    int mergedCount = 0;
    mergedList[mergedCount][0] = arr[0][0];
    mergedList[mergedCount][1] = arr[0][1];
    mergedCount++;

    // Merge the intervals
    for (int i = 1; i < arrSize; i++) {
        if (is_overlapping(mergedList[mergedCount - 1], arr[i])) {
            mergedList[mergedCount - 1][1] = 
                mergedList[mergedCount - 1][1] > arr[i][1] ? mergedList[mergedCount - 1][1] : arr[i][1];
        } else {
            mergedList[mergedCount][0] = arr[i][0];
            mergedList[mergedCount][1] = arr[i][1];
            mergedCount++;
        }
    }

    *returnSize = mergedCount;
    return mergedList;
}

// Test the code
int main() {
    int arr[][2] = {{1, 3}, {2, 6}, {8, 10}};
    int arrSize = sizeof(arr) / sizeof(arr[0]);
    int returnSize;
    
    int** mergedIntervals = merge(arr, arrSize, &returnSize);

    // Print the merged intervals
    for (int i = 0; i < returnSize; i++) {
        printf("[%d, %d]\n", mergedIntervals[i][0], mergedIntervals[i][1]);
        free(mergedIntervals[i]); // Free allocated memory for each interval
    }
    free(mergedIntervals); // Free allocated memory for the merged list

    return 0;
}

Output:

[1, 6]
[8, 10]

Explanation:

Here are some of the pointers from the code I have written.

  • The is_overlapping function checks if two intervals overlap.
  • The compare function is used by qsort to sort the intervals by their first value.
  • The merge function sorts the intervals and then merges overlapping intervals.
  • Memory for the merged intervals is dynamically allocated.
  • The main function tests the code with the given example and prints the merged intervals, ensuring to free the allocated memory.

Merge Overlapping Intervals is one of the really interesting coding challenges. You can implement this program in any language of your choice like C/C++, Java, and Python. Let’s share your code in the comment section below.

Leave a Reply

Your email address will not be published. Required fields are marked *