Skip to content

Instantly share code, notes, and snippets.

@luizguilhermefr
Last active March 9, 2019 12:47
Show Gist options
  • Save luizguilhermefr/f6a3a3e807fbd540f1d36c398bc9abff to your computer and use it in GitHub Desktop.
Save luizguilhermefr/f6a3a3e807fbd540f1d36c398bc9abff to your computer and use it in GitHub Desktop.
PHP merge intervals
<?php
/*
* PHP7 implementation of merging intervals
* It will remove intersections between intervals, for example: [(1, 5), (3,8), (12, 15)] will turn
* into [(1, 8), (12, 15)].
* Based on: https://www.geeksforgeeks.org/merging-intervals/
*/
function merge_intervals(array $data) : array {
if (count($data) <= 1) {
return $data;
}
$stack = [];
$stack[] = $data[0];
for ($i = 1; $i < count($data); $i++) {
$top = end($stack);
if ($top['end'] < $data[$i]['start']) {
array_push($stack, $data[$i]);
} else if ($top['end'] < $data[$i]['end']) {
$top['end'] = $data[$i]['end'];
array_pop($stack);
array_push($stack, $top);
}
}
return $stack;
}
// Note: intervals must be sorted previously based on start
$d1 = [
[
'start' => 0,
'end' => 200
],
[
'start' => 150,
'end' => 250
],
[
'start' => 251,
'end' => 255
]
];
$r1 = merge_intervals($d1);
var_dump($r1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment