find if one string is a valid anagram of another , in scala Question is taken from leet code.

Problem

Given two strings s and t , write a function to determine if t is an anagram of s.

Examples

Input: s = "anagram", t = "nagaram"
Output: true

Input: s = "rat", t = "car"
Output: false


Here is my implementation in scala

import scala.collection.immutable.HashMap

object ValidAnagram extends App {
  def validAnagram(s1: String, s2: String): Boolean = {
    if (s1 == s2) true
    else if (s1.length != s2.length) false
    else {
      val lookupTable = s1.foldLeft(HashMap[Char,Int]()) ((m,c) =&gt; m ++ HashMap(c -&gt; (if (m contains c) m(c) + 1 else 1)))
      println(lookupTable)
      (s2.foldLeft(lookupTable) {(m,c) =&gt;
        if (m contains c) {
          val count = m(c)
          if (count &gt; 1) {m + (c -&gt; (count-1))} else m - c
        } else m  // we can return here if not functional
      }).isEmpty
    }
  }
    println(validAnagram(args(0), args(1)))
  }
Short circuit!

Check the lengths first. In the case that they aren't the same, you don't need to incur a linear pass for an equality check.

Don't check the hashmap for an entry!

It's good that you know m(c) can throw if there's a missing key; luckily, 
 you can use Map#getOrElse and provide a default -- in this case, it makes sense to provide a 0 default since you haven't seen the character.

Compare the counts from each string directly!

I find the subtracting of the counts to be very confusing. You'll need to remove keys from the counter if any of the values go to 0, which lowers the signal to noise ratio of the code. It's better to just build a second counter.



If you decide to build two counters and compare them, you'll need to do the same fold logic twice. This is really messy to write, so you won't want to do this twice. You may want to pimp out the String class. You can do this in the following way:

implicit class Counter(s: String) {
  def countCharacters: Map[Char, Int] = 
    s.foldLeft(Map.empty[Char, Int])({ case (acc, c) =&gt;
      acc + (c -&gt; (acc.getOrElse(c, 0) + 1))
    })
}


You can see it in action here:

scala&gt; "hello".countCharacters
res0: Map[Char,Int] = Map(h -&gt; 1, e -&gt; 1, l -&gt; 2, o -&gt; 1)


So now you can compare the counts with a clean, non-repeated API.

Pulling this all together, you can write:

object ValidAnagram extends App {

  // when I see a string, implicitly construct a `Counter` instance
  implicit class Counter(s: String) {
    // this will be "added" to the String API via an implicit class construction
    def countCharacters: Map[Char, Int] = 
      s.foldLeft(Map.empty[Char, Int])({ case (acc, c) =&gt;
        acc + (c -&gt; (acc.getOrElse(c, 0) + 1))
      })
  }

  def validAnagram(s1: String, s2: String): Boolean =
    if (s1.length != s2.length) false
    else if (s1 == s2) true
    else s1.countCharacters == s2.countCharacters


  println(validAnagram(args(0), args(1)))
}