How to check whether each substring range (L to R) from an array of substring ranges is a palindrome in Scala

1 Answer

0 votes
object PalindromeChecker {

  // Check if a substring of s from left to right (inclusive) is a palindrome
  def isPalindrome(s: String, left: Int, right: Int): Boolean = {
    var l = left
    var r = right

    while (l < r) {
      if (s(l) != s(r)) return false
      l += 1
      r -= 1
    }
    
    true
  }

  // Check and print whether substrings defined by ranges are palindromes
  def checkRangesForPalindrome(s: String, ranges: Seq[(Int, Int)]): Unit = {
    for ((start, end) <- ranges) {
      val substring = s.slice(start, end + 1)
      val result = if (isPalindrome(s, start, end)) "Palindrome" else "Not palindrome"
      println(s"$substring: $result")
    }
  }

  def main(args: Array[String]): Unit = {
    val s = "abcddcbeebc"
    val ranges = Seq((2, 5), (5, 10), (3, 7))

    checkRangesForPalindrome(s, ranges)
  }
}



/*
run:

cddc: Palindrome
cbeebc: Palindrome
ddcbe: Not palindrome

*/

 



answered Nov 17, 2025 by avibootz

Related questions

...