Last active
May 7, 2023 21:01
-
-
Save smarenkov/e398a0ab76f1709c9f978a8f244684e6 to your computer and use it in GitHub Desktop.
Solving a problem from an interview about merge intervals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<List<int>> mergeIntervals(List<List<int>> intervals) { | |
//The intervals should be sorted | |
//Creating a clone of intervals if we don't want the original intervals to be sorted | |
final clonedIntervals = List.from(intervals) | |
..sort((a, b) => a.first.compareTo(b.first)); | |
List<List<int>> mergedIntervals = []; | |
mergedIntervals.add(clonedIntervals.first); | |
for (final interval in clonedIntervals) { | |
final lastMergedIntervals = mergedIntervals.last; | |
if (lastMergedIntervals.last < interval.first) { | |
mergedIntervals.add(interval); | |
continue; | |
} | |
if (lastMergedIntervals.last < interval.last) { | |
mergedIntervals.remove(lastMergedIntervals); | |
mergedIntervals.add([lastMergedIntervals.first, interval.last]); | |
} | |
} | |
return mergedIntervals; | |
} | |
void main() { | |
final intervals = [[2, 3], [2, 6], [8, 10], [15, 18]]; | |
final mergedIntervals = mergeIntervals(intervals); | |
print("Original intervals: $intervals"); | |
print("Merged intervals: $mergedIntervals"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment