DEV Community


Discussion on: Daily Challenge #304 - Consecutive Letters

willsmart profile image

It's always nice to avoid a second iteration over elements if possible and efficient. This could allow a function to be applied on a stream/very-large-string, makes analysis of it easier, and just avoids having it do unnecessary work on elements it doesn't strictly need to deal with.
Here's a single loop TS implementation that will early exit as soon as it finds an element that...

  • has been seen before, or...
  • makes the new max char code too distant from the new min char code

If the whole string has been covered and the call to every didn't early exit, then all letters must be distinct (rule two covered), and the max code minus the min code must be less than the length of the string (they're all different to each other so this bound means they must be adjacent, rule one covered)

const solve = (s: string): boolean => {
  let minCode = Infinity,
    maxCode = -Infinity,
    seenChars = new Set<string>(),
    code: number;
  return [...s].every(
    c =>
      !seenChars.has(c) &&
        (code = c.charCodeAt(0)),
        (minCode = Math.min(code, minCode)),
        (maxCode = Math.max(code, maxCode)),
        maxCode - minCode < s.length
Enter fullscreen mode Exit fullscreen mode

Tested in kata

Edit: refactor to get rid of that sneaky arrayifying spread operator...

const solve = (s:string): boolean => {
  let minCode = Infinity,
    maxCode = -Infinity,
    seenChars = new Set<string>();
  for (const c of s) {
      if (seenChars.has(c)) return false;
      const code = c.charCodeAt(0);
      minCode = Math.min(code, minCode);
      maxCode = Math.max(code, maxCode);
      if (maxCode - minCode >= s.length) return false;
  return true;
Enter fullscreen mode Exit fullscreen mode
bugb profile image

It's always nice to avoid a second iteration

We also have space complexity

  • if 2 loops O(2n) and the space is O(1) then it still good to give a try
  • if you have only one loop but the space is O(n) or O(n^2), you should consider to use then ;)
willsmart profile image

You're right, space is part of the equation too. It's all about what tradeoffs you're happy to make.

In this case, we're checking for duplicates in the string so we're either storing a memo hash (O(n) on space) or iterating over the pairs of elements (O(n^2) on time).
This one is O(n) on space and time, but you could defn make a fn that was O(1) on space if you were ok with O(n^2) on time.

(O(n) == O(2n) btw. The notation includes a multiplier to cover differences in the base case. So the top function up there where [...s] implicitly loops through the string before even hitting the every, actually has the same complexity as the lower function that is genuinely just one loop.)