DEV Community

Martin Nordström
Martin Nordström

Posted on

Javascript Algorithms Challenges | Part 2

Hey again!

This is the second part of my Javascript coding challenges and I'm super excited to get into it. I want to thank you all for the very kind response that I got in my first article and I especially want to thank the Dev.to team for featuring it on their Twitter!

If you haven't read the first one, you can do it here: Javascript Algorithms Challenges | Part 1

Let's get into the challenges now! :-)

Prerequisites

I will be using Node.js to run the Javascript code, so you should install that before continuing.

I have created some start code for this article so you can get started quick! Here it is:

/*
Author: Martin Nordström
Created: 2018/04/07 
Keep coding!
*/

// MAX CHARACTER CHALLENGE
// Return the character that is most common in a string
function maxCharacter(str) {}

// FIZZBUZZ CHALLENGE
// Write a program that prints all the numbers from 1 to 100. For multiples of 3, instead of the number, print "Fizz", for multiples of 5 print "Buzz". For numbers which are multiples of both 3 and 5, print "FizzBuzz".
function fizzBuzz() {}
Enter fullscreen mode Exit fullscreen mode

When you have Node.js installed and the start code you are ready to go! :-)

Challenge 1 — Max character

There's a lot of different ways you can approach and solve this problem. I want to show you one that is kinda complicated, but I believe it's a really good way to better up your skills and show off if you are getting this problem at an interview.

What we need to do is show the most common character in a string. For example:

maxCharacter('lollipop') == 'l'

As you can see the most used character in the string lollipop is l.

We are first going to create an object as a map. So we will be creating an empty object.

function maxCharacter(str) {
  const charMap = {};
}
Enter fullscreen mode Exit fullscreen mode

After that, we want to loop through the string as an array. We first use the split() method to make the string into an array and then use forEach() to loop through every index in the array. Note that we need to provide forEach() a function that it will call each iteration.

function maxCharacter(str) {
  const charMap = {};

  str.split('').forEach((char) => {

  });
}
Enter fullscreen mode Exit fullscreen mode

We want to look through each key-value pair since it's going to be key-value pairs of the actual character and how many of them that are inside. So if the key exists we want to add 1 to it so we can see which one is the biggest. And if no character has been found yet, like the first character of the string, we just want to add 1 to it.

function maxCharacter(str) {
  const charMap = {};

  str.split('').forEach((char) => {
    if (charMap[char]) {
      charMap[char]++; // This will add 1
   } else { // If no letter has been found yet
       charMap[char] = 1;
      }
  });
}
Enter fullscreen mode Exit fullscreen mode

If we try to run this function with the string lollipop we will get:

{ l: 3, o: 2, i: 1, p: 2 }

As you can see it does notice wich character is most used in the string! Which is l in this case.

By the way! I'm calling the function like this:

const output = maxCharacter('lollipop');

console.log(output);
Enter fullscreen mode Exit fullscreen mode

Since it doesn't work if I don't and if you know why please let me know!!

Now we have to return the character that is most common in the string. For that, I will be using a for in loop, which is used to loop through an object, instead of an array. We also going to add two more variables. maxChar and maxNum. They will both equal "nothing", meaning empty string an just a 0. maxChar is going to be the actual number that has the most occurrences and maxNum will be that number. So for lollipop maxNum will be 2 and maxChar is going to be l.

I should also say that we will create the variables with let and not const since the values of the variables will change.

We can check that with an if statement:

for (let char in charMap) {
  if (charMap[char] > maxNum) {
    maxNum = charMap[char];
    maxChar = char;
  }
}
Enter fullscreen mode Exit fullscreen mode

Here we are checking if the key is greater than the maxNum (which it will be the first iteration). So we will set maxNum to the actual value and then we will set the maxChar to the actual character. And then just return the maxChar.

What we will have is this:

function maxCharacter(str) {
  const charMap = {};
  let maxNum = 0;
  let maxChar = '';

  str.split('').forEach((char) => {
    if (charMap[char]) {
      charMap[char]++; // This will add 1
   } else { // If no letter has been found yet
       charMap[char] = 1;
      }
  });

  for (let char in charMap) {
    if (charMap[char] > maxNum) {
      maxNum = charMap[char];
      maxChar = char;
    }
  }
  return maxChar;
}

const output = maxCharacter('lollipop');

console.log(output); // Gives us l in this case
Enter fullscreen mode Exit fullscreen mode

Congrats! You now know how to check the most common character in a string with Javascript!

Challenge 2 — Fizzbuzz

The last challenge for this article is a popular one and you probably have heard of this. It's super popular in interviews and in schools. I did this in C++ once in my programming class for example.

What we first going to do is create a for loop. And in the for loop we are going to set a variable to 1 and say that as long as that variable is less, or equal to 100 we will keep looping and lastly we also want to increment that variable.

function fizzBuzz() {
  for (let i = 1; i <= 100; i++) {
    console.log(i) // 1,2,3,4,5,6,7,8....100
  }
}
Enter fullscreen mode Exit fullscreen mode

What we want to happen is every multiple of 3 (3, 6, 9, 12 etc) we want to print the word fizz. And every multiple of 5 (5, 10, 15, 20 etc) we want to print the word buzz. And every time we get the same multiple for the two numbers, like 15 we want to print fizzbuzz.

If you know how to use the modulus operator you can solve this pretty quickly and easily.

We are just going to create an if statement that looks like this:

if (i % 3 === 0) {
  console.log('fizz');
} else {
  console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

Modulus will just give us a remainder and if there's no remainder it's a multiple. Otherwise, we will just output the number. If we run this we will get the following output:

1
2
fizz
4
5
fizz
7
8
fizz
10
11
fizz
Enter fullscreen mode Exit fullscreen mode

And as you can see, no 3 or 6 or 9 etc!

For the number 5, we can just create an else if` statement inside of the if statement. And replace the 3 with 5 in this case. Like this:


if (i % 3 === 0) {
console.log('Fizz');
} else if (i % 5 === 0) {
console.log('Buzz');
} else {
console.log(i);
}

And that will give us:


1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz // Gotta fix this!!

It works! But we need to fix that every time there's a multiple of 3 and 5 together we want to print put FizzBuzz. As you can see, the number 15 is being printed out as Fizz which is no bueno.

What we can do is make our current if statement an else if statement, because we want to check if there are any "FizzBuzz" numbers out there first.

`
if (i % 3 === 0 && i % 5 === 0) {
console.log('FizzBuzz');
} else if (i % 3 === 0) {
console.log('Fizz');
} else if (i % 5 === 0) {
console.log('Buzz');
} else {
console.log(i);
}

`

This will give us:


1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

And that's it! You have now completed the famous FizzBuzz challange!

Also, you can shorten this up a little bit by replacing
if (i % 3 === 0 && i % 5 === 0) with if (i % 15 === 0)
Because if it's a multiple of 15 it will be a multiple by 3 and 5.

Last Remarks

Thank you for reading the second part of my “Javascript Algorithms Challenges” series. I hope you have learned something new that you might be able to use later in the future! I will try to find more fun and instructive challenges. So please follow me here or on my other social media platforms to get news about the upcoming articles!

Martin Nordström

Instagram | Twitter | Github

Top comments (9)

Collapse
 
patriklarsson profile image
Patrik • Edited

Love this article and it's a great primer for someone to start solving these problems.

Just because I love to see iterative improvements, can I suggest you move the check for maxChar into your first loop to avoid the second. With a reduce you could instead do:

function maxCharacter(str) {
    var maxNum = 0,
        maxChar;

    str.split('').reduce((letters, letter) => {
        if (!letters[letter]) {
            letters[letter] = 0;
        }
        letters[letter]++;

        if (letters[letter] > maxNum) {
        maxChar = letter;
            maxNum = letters[letter];
        }

        return letters;
    }, []);

    return maxChar;
}
Collapse
 
martinnrdstrm profile image
Martin Nordström

Thanks for your suggestion Patrick!

Smart move with using the reduce method and moving the check!

Collapse
 
joelnet profile image
JavaScript Joel • Edited

A solution using reduce:

// Note: this function (like the original) does not take into consideration a tie.
const charCountHashTable = (str = '') =>
  Array.prototype.reduce.call(str, (acc, x) => {
    // increment count
    acc.count[x] = ~~acc.count[x] + 1

    // set 'most' to larger value
    acc.most = acc.count[x] > ~~acc.count[acc.most] ? x : acc.most

    return acc
  }, { count: {}, most: null })

charCountHashTable('lollipop')
//=> { count: { l: 3, o: 2, i: 1, p: 2}, most: 'l' } }
Collapse
 
kepta profile image
Kushan Joshi • Edited

My code golf to get the maxCharacter

const maxCharacter = string =>
  [...string]
    .map(char => [char, string.split(char).length])
    .reduce(
      ([maxChar, maxOcc], [c, o]) => (maxOcc < o ? [c, o] : [maxChar, maxOcc])
    );

maxCharacter('lollipop'); // ['l', 4]

I agree it is terse, but if you love coding wizardry you might see the beauty in it <3. (The secret is to avoid variables and keeping it simple)

Collapse
 
gmartigny profile image
Guillaume Martigny

Hi,
Just a minor nitpicking, you can format your code for a better reading experience.
On your markdown, you can specify the language use next to the opening back-tick.
github.com/adam-p/markdown-here/wi...

Happy coding

Collapse
 
l7ucian profile image
Andercou Lucian

I've run this snippet :

function maxCharacter(str) {
const charMap = {};

str.split('').forEach((char) => {
if (charMap[char]) {
charMap[char]++; // This will add 1
} else { // If no letter has been found yet
charMap[char] = 1;
}
});
}

and the function returns undefined unless I return charMap.
This seems like a slight mistake.

Collapse
 
aralroca profile image
Aral Roca

Cool! Great job 😊 I recommend you Codility to practice more algorithms challanges; app.codility.com/programmers/lessons/

Collapse
 
martinnrdstrm profile image
Martin Nordström

Thanks Aral!

Will definitely check that out!

Collapse
 
lalegamero profile image
Alex Gamero

This article is "muy bueno"!! Great job, Martin. Thank you so much! :)