Drill

ProblemsJavaScript › patterns

The longest run with only two kinds

hardpatternsSliding windowStringsHash mapsJavaScript

A packing line can hold two product types at once before it has to be cleaned down. Given the day’s sequence, find the longest run it could have handled without a change-over.

longestTwoFlavourRun(sequence: string) → int

Solve it in the editor →

Where you start

function longestTwoFlavourRun(sequence) {
  
}

Worked examples

CallResult
longestTwoFlavourRun("aabbcc")4
longestTwoFlavourRun("abcbbbbcccbdddadacb")10
longestTwoFlavourRun("aaaa")4
longestTwoFlavourRun("ab")2

Hint

Grow a window to the right, keeping a count per character inside it. When a third kind appears, pull the left edge in until one kind is gone.

Reference solution in JavaScript
function longestTwoFlavourRun(sequence) {
  const counts = new Map();
  let left = 0;
  let best = 0;
  for (let right = 0; right < sequence.length; right += 1) {
    const ch = sequence[right];
    counts.set(ch, (counts.get(ch) ?? 0) + 1);
    while (counts.size > 2) {
      const out = sequence[left];
      const left_n = counts.get(out) - 1;
      if (left_n === 0) counts.delete(out);
      else counts.set(out, left_n);
      left += 1;
    }
    const span = right - left + 1;
    if (span > best) best = span;
  }
  return best;
}

The same problem in another language

More patterns problems in JavaScript