Skip to content

Instantly share code, notes, and snippets.

@lyquocphong
Created January 21, 2021 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lyquocphong/f1297463852d5fce675496f7be3ed743 to your computer and use it in GitHub Desktop.
Save lyquocphong/f1297463852d5fce675496f7be3ed743 to your computer and use it in GitHub Desktop.
Minimum window substring
<?php
$str = 'abbaacdbcab';
$chars = ['a', 'b', 'c'];
echo "Expected: bca | Result: ".findMinWinSubString($str, $chars)."\n";
$str = 'xyyzyzyx';
$chars = ['x', 'y', 'z'];
echo "Expected: xyz | Result: ".findMinWinSubString($str, $chars)."\n";
function findMinWinSubString($str, $chars) {
$right = 0;
$left = 0;
$checkWindow = [];
$uniqueCounter = 0;
$requiredCounter = count($chars);
foreach($chars as $char) {
if (!isset($checkWindow[$char])) {
$checkWindow[$char] = 0;
}
$checkWindow[$char] += 1;
}
$minWindow = [];
while ($right < strlen($str)) {
$char = $str[$right];
if (!isset($minWindow[$char])) {
$minWindow[$char] = 0;
}
if (in_array($char, $chars) && $minWindow[$char] == 0) {
$uniqueCounter += 1;
}
$minWindow[$char] += 1;
while ($uniqueCounter == $requiredCounter) {
$length = $right - $left + 1;
if ($length === $uniqueCounter && $uniqueCounter == $requiredCounter) {
return substr($str, $left, $length);
}
$headChar = $str[$left];
$minWindow[$headChar] -= 1;
if ($minWindow[$headChar] == 0 && in_array($headChar, $chars)) {
$uniqueCounter -= 1;
}
$left += 1;
}
$right += 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment