Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,844 questions

51,765 answers

573 users

How to get all the substrings with exactly k distinct characters from a given string in Scala

1 Answer

0 votes
object SubstringsWithKDistinct {

  // Function to get all substrings with exactly k distinct characters
  def getSubstringsWithKDistinct(s: String, k: Int): List[String] = {
    val n = s.length
    var listOfSubstrings = List.empty[String]

    // Iterate over all possible starting points of substrings
    for (i <- 0 until n) {
      val freqMap = scala.collection.mutable.Map.empty[Char, Int] // map for character frequencies
      var distinctCount = 0                                       // counter for distinct characters

      // Extend the substring from position i to j
      for (j <- i until n) {
        val ch = s(j)

        // If character is new to the substring, increment distinct count
        if (!freqMap.contains(ch)) {
          distinctCount += 1
          freqMap(ch) = 0
        }

        freqMap(ch) = freqMap(ch) + 1

        // If we have exactly k distinct characters, store the substring
        if (distinctCount == k) {
          listOfSubstrings = listOfSubstrings :+ s.substring(i, j + 1)
        }
        // If we exceed k distinct characters, stop exploring this substring
        else if (distinctCount > k) {
          // break out of inner loop
        }
      }
    }

    listOfSubstrings
  }

  def main(args: Array[String]): Unit = {
    val str = "characters"
    val k = 4

    val substrings = getSubstringsWithKDistinct(str, k)

    println(s"Number of substrings with exactly $k distinct characters = ${substrings.length}\n")
    
    println(s"Substrings with exactly $k distinct characters in '$str':")
    substrings.foreach(println)
  }
}




/*
run:

Number of substrings with exactly 4 distinct characters = 9

Substrings with exactly 4 distinct characters in 'characters':
char
chara
charac
harac
aract
ract
acte
cter
ters

*/

 



answered Nov 14, 2025 by avibootz

Related questions

...