The average programmer is probably worse than you think

Today I came across a problem from code wars. Someone posted it online and felt bad because he’s always off from the best solutions, asking how can he improve.

Here’s the problem:

Count the number of Duplicates
Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string.

You can solve the problem yourself before continuing –

Here’s the solution, which is considered “best practice” and “clever” –

I don’t know from where to start. Gladfully, many people commented on the post saying it is not very readable, but they were very reserved about it. Excuse me for being blunt, this code is crap. If you write like that in an interview, there is a slim chance you will pass, which is only if the company likes its code obscure and unmanageable.

You would think this one-liner-magic is at least a very good solution right? No. It’s not even that. What is the complexity of the solution? O(nlogn) because of the sorting operation. Which is far from optimal.

Here is my solution, which can still be improved, although even now is much much better than the “best practice”.

def duplicate_count(text: str) -> int:
    letters_counter = {}

    for letter in text.lower():
        letters_counter[letter] = letters_counter.get(letter, 0) + 1

    duplications = len([value for value in letters_counter.values() if value > 1])

    return duplications

Average complexity of O(n), and less pain in the eyes.

Don’t learn from something just because it’s get upvoted by many 15 years old high-schoolers. Code clean.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: