String Reductions – HackerRank Solution

In this post, we will solve String Reductions HackerRank Solution. This problem (String Reductions) is a part of HackerRank Functional Programming series.


Given a string, str = s1, s2, . . . , sn, consisting of n lowercase English characters (az), remove all of the characters that occurred previously in the string. Formally, remove all characters, si, for:

 j, sj = si and j < i

Input Format

A single line of input containing a string str of length n.


  • 1 <= n <= 105
  • si = {a, b, . . . , z}, where 1 <= i <= n

Output Format

Print the string after removing all the characters that occurred previously.

Sample Input #00


Sample Output #00


Sample Input #01


Sample Output #01


Sample Output #02


Sample Output #02



Test case #00: For str = “accabb, characters at indexes 3, 4, 6 are removed as they have already occurred.
Test case #01: As each character occurs only once, nothing is removed.
Test case #02: For str = “pprrqq, each character occurs twice. The second of these characters is removed. Characters at positions 2, 4 and 6 are removed.

Solution – String Reductions – HackerRank Solution


import java.util.Scanner

object Solution {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(

    val s = sc.nextLine


    def solve(s: String): String = {
      def inner(s: List[Char], used: Set[Char], acc: List[Char]): String = s match {
        case Nil => acc.reverse.mkString("")
        case c :: cs => if (used.contains(c)) inner(cs, used, acc) else inner(cs, used + c, c :: acc)

      inner(s.toList, Set(), Nil)


Note: This problem (String Reductions) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *