Back to Freecodecamp

Challenge 207: Smallest Gap

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a863194f1f4e63f645e.md

latest1.8 KB
Original Source

--description--

Given a string, return the substring between the two identical characters that have the smallest number of characters between them (smallest gap).

  • There will always be at least one pair of matching characters.
  • The returned substring should exclude the matching characters.
  • If two or more gaps are the same length, return the characters from the first one.

For example, given "ABCDAC", return "DA" because:

  • Only "A" and "C" repeat in the string.
  • The number of characters between the two "A" characters is 3, and between the "C" characters is 2.
  • So return the string between the two "C" characters.

--hints--

smallestGap("ABCDAC") should return "DA".

js
assert.equal(smallestGap("ABCDAC"), "DA");

smallestGap("racecar") should return "e".

js
assert.equal(smallestGap("racecar"), "e");

smallestGap("A{5e^SD*F4i!o#q6e&rkf(po8|we9+kr-2!3}=4") should return "#q6e&rkf(p".

js
assert.equal(smallestGap("A{5e^SD*F4i!o#q6e&rkf(po8|we9+kr-2!3}=4"), "#q6e&rkf(p");

smallestGap("Hello World") should return "".

js
assert.equal(smallestGap("Hello World"), "");

smallestGap("The quick brown fox jumps over the lazy dog.") should return "fox".

js
assert.equal(smallestGap("The quick brown fox jumps over the lazy dog."), "fox");

--seed--

--seed-contents--

js
function smallestGap(str) {

  return str;
}

--solutions--

js
function smallestGap(str) {
  let minGap = Infinity;
  let result = "";

  for (let i = 0; i < str.length; i++) {
    for (let j = i + 1; j < str.length; j++) {
      if (str[i] === str[j]) {
        const gap = j - i - 1;

        if (gap < minGap) {
          minGap = gap;
          result = str.slice(i + 1, j);
        }

        break;
      }
    }
  }

  return result;
}