Skip to content

Instantly share code, notes, and snippets.

@matchilling
Last active June 4, 2017 16:35
Show Gist options
  • Save matchilling/44d11ca390284f89cfc6 to your computer and use it in GitHub Desktop.
Save matchilling/44d11ca390284f89cfc6 to your computer and use it in GitHub Desktop.
Merge sorted arrays unique with runtime O(n)
/**
* Merge sorted arrays unique
*
* Function merges two sorted arrays A & B and produces a new sorted array C
* with all elements of A and B without repetitions.
*
* For instance, if
* A = [1, 1, 2, 2, 5, 7, 16] and
* B = [2, 5, 10, 10, 11, 12, 14, 16],
* then
* C = [1, 2, 5, 7, 10, 11, 12, 14, 16].
*
* @param array $a
* @param array $b
* @return array
*/
function array_merge_unique(array $a, array $b)
{
$m = count($a);
$n = count($b);
$res = array();
$i = 0;
$j = 0;
$k = 0;
while ($i < $m && $j < $n)
{
if ($a[$i] === $b[$j])
{
if (0 === $k)
{
$res[] = $a[$i];
$k++;
}
elseif ($res[$k - 1] !== $a[$i])
{
$res[] = $a[$i];
$k++;
}
$i ++;
$j ++;
}
elseif ($a[$i] < $b[$j])
{
if (0 === $k)
{
$res[] = $a[$i];
$k++;
}
elseif ($res[$k - 1] !== $a[$i])
{
$res[] = $a[$i];
$k++;
}
$i ++;
}
else
{
if (0 === $k)
{
$res[] = $b[$j];
$k++;
}
elseif ($res[$k - 1] !== $b[$j])
{
$res[] = $b[$j];
$k++;
}
$j ++;
}
}
for ($i; $i < $m; $i ++)
{
if ($res[$k - 1] !== $a[$i])
{
$res[] = $a[$i];
$k++;
}
$i++;
}
for ($j; $j < $n; $j ++)
{
if ($res[$k - 1] !== $b[$j])
{
$res[] = $b[$j];
$k++;
}
$j++;
}
return $res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment