DEV Community

loading...

Discussion on: Daily Challenge #12 - Next Larger Number

Collapse
peter279k profile image
peter279k

Here is my simple solution with PHP:

function nextBigger($n) {
  // your code here
  if (strlen($n) === 1) {
    return -1;
  }

  $answer = 0;
  $maxNumber = findMaxNumber($n);

  if ($maxNumber === $n) {
    return -1;
  }

  $nInfoArray = [];
  $strCountArray = [];

  $index = 0;
  $str = (string)$n;
  for (; $index < strlen($str); $index++) {
    if (array_key_exists((string)$str[$index], $nInfoArray) === true) {
      $nInfoArray[(string)$str[$index]] += 1;
    } else {
      $nInfoArray[(string)$str[$index]] = 1;
      $strCountArray[(string)$str[$index]] = 0;
    }
  }

  for ($min=$n+1; $min<=$maxNumber; $min++) {
    $str = (string)$min;
    $strIndex = 0;
    $findAlert = false;
    for(; $strIndex<strlen($str); $strIndex++) {
      if (strpos((string)$n, (string)$str[$strIndex]) !== false) {
        $strCountArray[(string)$str[$strIndex]] += 1;
        if ($strCountArray[(string)$str[$strIndex]] > $nInfoArray[(string)$str[$strIndex]]) {
            $findAlert = true;
        }
      } else {
        $findAlert = true;
        break;
      }
    }

    foreach ($strCountArray as $key => $value) {
      $strCountArray[$key] = 0;
    }

    if ($findAlert === true) {
      continue;
    }

    $answer = $min;
    break;
  }

  if ($answer === $n) {
    return -1;
  }

  return $answer;
}

function findMaxNumber($n) {
  $maxNumberArray = [];
  $string = (string)$n;

  for($index=0; $index<strlen($string); $index++) {
    $maxNumberArray[] = $string[$index];
  }

  sort($maxNumberArray);

  $maxNumberArray = array_reverse($maxNumberArray);

  return (int)implode($maxNumberArray);
}