Back to Freecodecamp

Challenge 207: Smallest Gap

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

latest2.1 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--

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

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(smallest_gap("ABCDAC"), "DA")`)
}})

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

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(smallest_gap("racecar"), "e")`)
}})

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

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(smallest_gap("A{5e^SD*F4i!o#q6e&rkf(po8|we9+kr-2!3}=4"), "#q6e&rkf(p")`)
}})

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

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(smallest_gap("Hello World"), "")`)
}})

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

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(smallest_gap("The quick brown fox jumps over the lazy dog."), "fox")`)
}})

--seed--

--seed-contents--

py
def smallest_gap(s):

    return s

--solutions--

py
def smallest_gap(s):
    min_gap = float("inf")
    result = ""

    for i in range(len(s)):
        for j in range(i + 1, len(s)):
            if s[i] == s[j]:
                gap = j - i - 1

                if gap < min_gap:
                    min_gap = gap
                    result = s[i + 1:j]

                break

    return result