All files / leetCode 0556.ts

100% Statements 21/21
100% Branches 8/8
100% Functions 1/1
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37  4x 4x 4x 4x     4x 12x 5x 5x 5x   12x 3x 9x     4x 1x     3x 3x 3x     3x             3x    
export default function nextGreaterElement(n: number): number {
  const digits = n.toString().split('')
  let exist = false
  let left = -1
  let right = -1
 
  // Find the first digit that is smaller than the digit on the top of the stack.
  for (let i = digits.length - 1, stack: number[] = []; i >= 0; i--) {
    while (stack.length && digits[i] < digits[stack[stack.length - 1]]) {
      exist = true
      left = i
      right = stack.pop() as number
    }
    if (exist)
      break
    stack.push(i)
  }
 
  if (exist === false)
    return -1
 
  // 158476531 => 158576431
  const digit = digits[left]
  digits[left] = digits[right]
  digits[right] = digit
 
  // 158576431 => 158513467
  const result = Number.parseInt(
    digits
      .slice(0, left + 1)
      .concat(digits.slice(left + 1).reverse())
      .join(''),
    10,
  )
  return result > 2 ** 31 - 1 ? -1 : result
}