DEV Community

Discussion on: A classic interview question

Collapse
 
jmfayard profile image
Jean-Michel πŸ•΅πŸ»β€β™‚οΈ Fayard • Edited

Hello!

How to check that two words are anagrams?

Should we

  1. sort the array?
  2. develop our own algorithm?

If I was on the hiring side, I am not sure I would have choosen a candidate who opt for the second solution and waste its time on algorithm trivia.

Have a look at this snippet and run it from pl.kotl.in/swFfcgRPy

fun main() {
    testAnagram("cinema", "iceman")
    testAnagram("algo-trivia", "knuth")
    benchmark()

/** Output
Are cinema and iceman anagrams? Yes
Are algo-trivia and knuth anagrams? No
It took 1118 milliseconds to sort an array of 1000000 elements

**/
}

fun testAnagram(a: String, b: String) {
    val ok = a.toList().sorted()  == b.toList().sorted()
    println("Are $a and $b anagrams? " + if (ok) "Yes" else "No")
}

fun benchmark() {
    val arraySize = 1_000_000
    val bigList = List(arraySize) { Random.nextInt() }

    val benchmark = measureTimeMillis {
      bigList.sorted()
    }
    println("It took $benchmark milliseconds to sort an array of $arraySize elements")
}

As you can see, your first intuition was right.

Sorting an array is a bulletproof way to check that two words are an anagram.

Now if we are talking about the price of things, the first solution is the optimal one.

Words are usually very small lists. Even German words.

Let's assume I have alien words of 1 million characters.
That still takes less close to no time at all to sort out.
Who cares? Not the business.

On the other hand, a smart business does not particularly like developers who reinvent wheels.
Such a developer will spend much more than one second reinventing an algorithm for this.
It might be buggy, which means that the business will have to go through the complete lifecycle of having a client report a bug, file a jira ticket, wait that someone is ready, fix it, do a release, announce it.

It's important to udnerstand that your time isn't free and is, in fact, quite expansive.

So a smart business should in my opinion gives it thumbs up to a candidate that use the .sort() function from the standard library.