1
\$\begingroup\$

Given a string, find the first repeating character in it.

Examples:

  • firstUnique("Vikrant")None
  • firstUnique("VikrantVikrant")Some(V)

Scala implementation:

object FirstUniqueChar extends App {
 def firstUnique(s: String): Option[Char] = {
 val countMap = (s groupBy (c=>c)) mapValues(_.length)
 def checkOccurence(s1: String ): Option[Char] = {
 if (countMap(s1.head) > 1) Some(s1.head)
 else if (s1.length == 1) None
 else checkOccurence(s1.tail)
 }
 checkOccurence(s)
 }
 println(firstUnique("abcdebC"))
 println(firstUnique("abcdef"))
}

I also have a followup question. What is the recommended way if I do not want to solve this problem with recursion? Instead of using the checkOccurence method I can traverse through the string and break when I find the first element with a count more than 1. But that will require a break, which is discouraged in Scala.

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jan 9, 2019 at 0:53
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

Your checkOccurrence(s) is just a clumsy way to write s.find(countMap(_)> 1).

You can significantly simplify the solution by taking advantage of .distinct.

def firstUnique(s: String): Option[Char] =
 s.zipAll(s.distinct, '\u0000', '\u0000')
 .collectFirst({ case ab if ab._1 != ab._2 => ab._1 })
answered Jan 9, 2019 at 21:04
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Slightly more concise syntax for a very nice answer: collectFirst{case (a,b) if a != b => a} \$\endgroup\$ Commented Jan 10, 2019 at 1:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.