code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

02 Find Smallest Letter Greater Than Target

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const findSmallestLetterGreaterThanTarget = (letters, target) => {
  if (letters[0] > target || letters[letters.length - 1] <= target) {
    return letters[0]
  }
  let start = 0
  let end = letters.length - 1
  while (start < end) {
    const mid = Math.trunc((end + start) / 2)
    console.log(start, end, mid, letters[mid])
    if (letters[mid] > target) {
      end = mid
    } else {
      start = mid + 1
    }
  }
  return letters[start]
}

console.log(findSmallestLetterGreaterThanTarget(['c', 'f', 'j'], 'k'))

Created 2022-03-18T07:03:34+00:00 · Edit