Skip to content

Instantly share code, notes, and snippets.

@smarenkov
Last active May 7, 2023 21:01
Show Gist options
  • Save smarenkov/e398a0ab76f1709c9f978a8f244684e6 to your computer and use it in GitHub Desktop.
Save smarenkov/e398a0ab76f1709c9f978a8f244684e6 to your computer and use it in GitHub Desktop.
Solving a problem from an interview about merge intervals
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