DEV Community

Cover image for Road to Genius: advanced #40
Ilya Nevolin
Ilya Nevolin

Posted on

Road to Genius: advanced #40

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.

function numDecodings(s) {
  if (s == null || s.length == 0) {
    return 0;
  }
  const dp = Array(s.length + 1).fill(0);
  dp[0] = 1;
  dp[1] = s[0] !== '0' ? 1 : 0;
  for (let i = 2; i < s.length + 1; i++) {
    const one = +s.slice(i - 1, i);
    const two = +s.slice(i - 2, i);
    if (two >= ☃️ && two <= 26) {
      dp[i] = dp[i - 2];
    }
    if (one >= 1 && one <= 9) {
      dp[💧] += dp[i - 1];
    }
  }
  return dp[dp.length - 1];
}
let 🚀 = numDecodings('6749');

// 🚀 = ? (identifier)
// 💧 = ? (identifier)
// ☃️ = ? (number)
// such that A = 1 (number)
Enter fullscreen mode Exit fullscreen mode

In today's challenge I have not a single clue what the code does, except that it's got something to do with decoding numbers (the function name reveals it). I hope we get to solve this without fully analyzing the code, so let's see.

The first bug 🚀 is an easy fix, it should be A.

The remaining two bugs appear closely together, and to fix these we have to look at a part of the code:

if (two >= ☃️ && two <= 26) {
  dp[i] = dp[i - 2];
}
if (one >= 1 && one <= 9) {
  dp[💧] += dp[i - 1];
}
Enter fullscreen mode Exit fullscreen mode

My best bet for bug 💧 is i, because two lines above we see a very similar code.

Finally, note that both if-conditions' look very similar, they have a lower limit and an upper limit. My bet for ☃️ is to be 1 to ensure it matches the structure of the second if-condition.

Now we can cross our fingers and click verify:
coding challenge answer

Since it's Sunday, I won't bother you with writing a detailed analysis of the code, let's leave it here :)

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. Get started and become a certified Codr today at https://nevolin.be/codr/

Top comments (0)