DEV Community

Discussion on: Daily Challenge #304 - Consecutive Letters

Collapse
 
qm3ster profile image
Mihail Malo • Edited

JavaScript

Efficient (for small strings)

works because if there are as many distinct characters as the length, there can't be duplicates

const solve = str => {
  const len = str.length
  let v = str.charCodeAt()
  for (let i = 1; i < len; i++) if (str.charCodeAt(i) < v) v = str.charCodeAt(i)
  for (let i = 0; i < len; i++) if (!str.includes(String.fromCharCode(v++))) return false
  return true
}
Enter fullscreen mode Exit fullscreen mode

TextEncoder

const enc = new TextEncoder('ascii')
const solve = str => {
  const buf = enc.encode(str)
  const len = buf.length
  buf.sort()
  let v = buf[0]
  for (let i = 1; i < len; i++) if (buf[i] !== ++v) return false
  return true
}
Enter fullscreen mode Exit fullscreen mode

TextEncoder but without sorting

const enc = new TextEncoder('ascii')
const solve = str => {
  const buf = enc.encode(str)
  const len = buf.length
  let v = buf.reduce(Math.min)
  for (let i = 0; i < len; i++) (buf.includes(v++)) return false
  return true
}
Enter fullscreen mode Exit fullscreen mode

TextEncoder without mutation

const enc = new TextEncoder('ascii')
const solve = str => {
  const buf = enc.encode(str)
  buf.sort()
  return !!buf.reduce((a, x) => x - a === 1 ? x : 0)
}
Enter fullscreen mode Exit fullscreen mode

TextEncoder but finally a oneliner

const solve = str => !!new TextEncoder('ascii')
  .encode(str)
  .sort()
  .reduce((a, x) => x - a === 1 ? x : 0)
Enter fullscreen mode Exit fullscreen mode