"Java LeetCode Challenge: Merging Intervals"

" 🚀 Day 45 of 50 – Java LeetCode Challenge " Today’s challenge was “56. Merge Intervals” — a classic array and sorting problem that sharpens your understanding of interval manipulation and greedy algorithms. The goal is to merge all overlapping intervals into distinct non-overlapping ranges. ⏱ Today’s Task – Merge Intervals 📝 Problem Statement: You are given an array of intervals where each interval is represented as [start, end]. Your task is to merge all overlapping intervals and return an array of the merged non-overlapping intervals. 🧪 Examples: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] ✅ Explanation: [1,3] and [2,6] overlap, so they merge into [1,6]. Input: intervals = [[1,4],[4,5]] Output: [[1,5]] ✅ Explanation: [1,4] and [4,5] are overlapping. Input: intervals = [[4,7],[1,4]] Output: [[1,7]] ✅ Explanation: Sorted first, then merged into one continuous interval. 🔧 Constraints: 1 <= intervals.length <= 10⁴ intervals[i].length == 2 0 <= start ≤ end ≤ 10⁴ 💻 My Java Solution: import java.util.*; class Solution {   public int[][] merge(int[][] intervals) {     if (intervals.length == 0) return new int[0][];           Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));     List<int[]> result = new ArrayList<>();           int[] current = intervals[0];     result.add(current);           for (int[] interval : intervals) {       if (interval[0] <= current[1]) {         current[1] = Math.max(current[1], interval[1]);       } else {         current = interval;         result.add(current);       }     }           return result.toArray(new int[result.size()][]);   } } 🔍 Takeaways: ✅ Smart use of sorting to arrange intervals by start time ✅ Use of greedy merging to efficiently combine overlapping ranges ✅ Clean and efficient O(n log n) time complexity due to sorting ✅ Handles all edge cases including adjacent and nested intervals 💡 Core Concepts: 📘 Sorting arrays with custom comparators 📘 Interval overlap detection 📘 Greedy algorithms and array manipulation 🎯 Day 45 completed — 5 more to go! 🚀 #Java #50DaysOfCode #LeetCode #ProblemSolving #Arrays #Sorting #GreedyAlgorithm #JavaProgramming #Day45 #CodeNewbie #LearnInPublic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories