Skip to main content

Command Palette

Search for a command to run...

Merge Intervals

Published
1 min read
Merge Intervals
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

Given an array of intervals where intervals[i] = [start<sub>i</sub>, end<sub>i</sub>], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

LeetCode Problem - 56

class Solution {
    public int[][] merge(int[][] intervals) {
        // If the input is empty, return an empty 2D array
        if (intervals.length == 0) {
            return new int[0][0];
        }

        // Sort the intervals based on the starting values
        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));

        // Create a list to hold the merged intervals
        List<int[]> merged = new ArrayList<>();

        // Initialize the current interval as the first interval in the sorted list
        int[] currentInterval = intervals[0];
        merged.add(currentInterval);

        // Iterate through each interval in the sorted list
        for (int[] interval : intervals) {
            int currentStart = currentInterval[0];
            int currentEnd = currentInterval[1];
            int nextStart = interval[0];
            int nextEnd = interval[1];

            // Check if the current interval overlaps with the next interval
            if (currentEnd >= nextStart) {
                // If they overlap, merge them by updating the end of the current interval
                currentInterval[1] = Math.max(currentEnd, nextEnd);
            } else {
                // If they don't overlap, move to the next interval and add it to the list
                currentInterval = interval;
                merged.add(currentInterval);
            }
        }

        // Convert the merged list to a 2D array and return it
        return merged.toArray(new int[merged.size()][]);
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.

Merge Intervals