DEV Community 👩‍💻👨‍💻

Cover image for Road to Genius: smart #27
Ilya Nevolin
Ilya Nevolin

Posted on

Road to Genius: smart #27

Each day I solve several coding challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.

coding challenge

Here's an interesting challenge, it's pretty short yet has some interesting properties. We have encountered similar code before many episodes ago, but this time we have to fully analyze it.

It starts with an empty object MP and a string T. The for-loop iterates over each character in T, the if-condition checks if that character has a key-entry in the MP object. If it doesn't it adds the key with 0 as value. Then it increments the value for that key by one.
At the end R = MP[T[4]]
This last line gets the value from MP by key that is the 4th index of T. This is a mouthful.

All that this code does it count the number of occurrences of characters of T. Since all characters in T are unique, MP's values will all equal to 1. Internally MP will look like this:

MP = {
  'j': 1,
  'p': 1,
  'n': 1,
  't': 1,
  'm': 1,
  'u': 1
}
Enter fullscreen mode Exit fullscreen mode

Let's have a closer look at the last line:
R = MP[T[4]]
We have to dissect it from the deepest end first:
T[4] this gets the character at index 4 from T, which is m.
Now we can substitute: R = MP['m']
We already know what MP's values are, so R will be 1.

coding challenge answer

By solving these challenges you train yourself to be a better programmer. You'll learn newer and better ways of analyzing, debugging and improving code. As a result you'll be more productive and valuable in business. Join me on the Road to Genius and upgrade your programming skills, at https://nevolin.be/codr/

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.