loading...

Javascript Algorithms Challenges | Part 1

martinnrdstrm profile image Martin Nordström ・6 min read

This is the beginning of a series I will be writting about coding challanges in Javascript and how to solve them (in SOME ways).

Alt text of image

Why even bother with reading this?

If you are planning on becoming a good programmer I bet some of you have plans on getting a job in the future. And when getting a job you have to go through a process, of which contains interviews and probably coding challenges. Some can be on a whiteboard at the company or on your computer at home. Companies usually do these types of tests because of:

  • It shows that you know your programming logic
  • It shows that you have critical thinking skills
  • It shows how you can work under pressure
  • It just shows the company a general picture of how you code

Therefore it’s good to know and get better at writing algorithms since it’s probably those the company want’s you to write.

I have therefore decided to start a series, “Javascript Algorithms Challenges”, where I will bring up different challenges and show how to solve them (in some ways) to make you get a better understanding about writing algorithms and understand them.

Prerequisites

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

I have created a Gist for this article so you can get started quick! Here it is:

/*
Author: Martin Nordström
Created: 2018/03/09 
Keep coding!
*/

// REVERSE A STRING CHALLENGE
// Return string in reverse
function reverseString(str) {}

// PALINDROME CHALLENGE
// Return true if palindrome and false if not
function isPalindrome(str) {}

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

Challenge 1 — Reverse a string

Since this challenge is pretty simple I will include a couple of ways on how to solve it so you can get an idea that there’s a lot of different ways to accomplish the same results. Here’s what we will start with:

function reverseString(str) {}

The first thing we could do is create a new variable and we’re going to set that to the string that’s passed in with split(). Since split() turns a string into an array and takes in a parameter of a separator. And because we want each character to be put in its own array value we will just be setting the parameter to ''. It will look like this:

function reverseString(str) {
  const strArray = str.split('');
}

Then we could use the array prototype method reverse() which will just reverse the array (smart right?). So let’s overwrite the current value.

function reverseString(str) {
const strArray = str.split('');
strArray.reverse();
}

To test this we can call the function and pass in a string to see what this gives us. And let’s not forget to put a console.log() at the bottom of the function.

function reverseString(str) {
  const strArray = str.split('');
  strArray.reverse();
  console.log(strArray);
}
reverseString('Hello Medium');
// Output:
[ 'm', 'u', 'i', 'd', 'e', 'M', ' ', 'o', 'l', 'l', 'e', 'H' ]

Now that we get the array in reversed order we can just turn it back to a regular string. And we can do this with join() which joins the elements of an array into a string and returns the string. We can also specify a separator like we did with split(). So let’s return the new string with the join() method applied. The code will then look like this:

function reverseString(str) {
  const strArray = str.split('');
  strArray.reverse();
  return strArray.join('');
}
reverseString('hello');
// Output: muideM olleH

This works fine, but it is really messy. We honestly don’t even need the strArray variable! What we can do to clean this up is to just chain these methods together, like this:

function reverseString(str) {
  return str.split('').reverse().join('');
}
reverseString('Hello Medium');
// Output: muideM olleH

Instead of using these methods we could also use the good old FOR loop! For this example we will be using a decrementing FOR loop.

The first thing we should do is create a new variable that contains an empty string that will host the new created string.

function reverseString(str) {
  let revString = "";  
}

The second step is to create the actual for loop. We will be using the str length, but like this: str.length — 1 since that it will correspond to the last letter in the string. In our case, “m”. We will also loop as long as i is greater than or equals 0 and decrement i after each iteration. Then add the newString variable to it’s self and to the index value of the array str. We also have to return the revString.

function reverseString(str) {
  let revString = "";

  for (let i = str.length - 1; i >= 0; i--) {
    revString += str[i];
  }

  return revString;

}
reverseString('Hello Medium');
// Output: muideM olleH

Congrats! You now know two ways to reverse a string in Javascript!

Alt text of image

Challenge 2— Palindrome

First, a palindrome is a word or a phrase that’s the same whether it’s forward or backward. Some examples:

  • Anna
  • A but tuba
  • Are we not pure? “No sir!” Panama’s moody Noriega brags. “It is garbage!” Irony dooms a man; a prisoner up to new era

So what we are going to do is to return true if the word or phrase is a palindrome or return false if it’s not a palindrome. Pretty simple stuff!

This is our starting block of code:

function isPalindrome(str) {}

The first we could do is reverse the string, set it’s value to a variable and since we already know how to do it this one will be super easy! I will go with our first solution since it’s the most practical (in my opinion).

function isPalidrom(str) {
  const revString = str.split('').reverse().join('');
}

And since a palindrome is the same thing forward as it is backward we can just check if the two different strings are equal!

function isPalidrom(str) {
  const revString = str.split('').reverse().join('');

  return revString === str;
}

We can also tidy up the code a little bit and of course call the function and pass in a string.

function isPalidrom(str) {
  return str === str.split('').reverse().join('');
}
isPalidrom('Hello Medium');
// Output: false

As you can see this will return false since “Hello Medium” is not a palidrom! But “Are we not pure? “No sir!” Panama’s moody Noriega brags. “It is garbage!” Irony dooms a man; a prisoner up to new era” is!

function isPalidrom(str) {
  return str === str.split('').reverse().join('');
}
isPalidrom('Are we not pure? “No sir!” Panama’s moody Noriega brags. “It is garbage!” Irony dooms a man; a prisoner up to new era');
// Output: true

One quick note thought! If we type in rAceCar it will return false since we have a capital C? and a capitalA`. But don’t worry, the fix is super easy!


function isPalidrom(str) {
str = str.toLowerCase();
return str === str.split('').reverse().join('');
}
isPalidrom('Are we not pure? “No sir!” Panama’s moody Noriega brags. “It is garbage!” Irony dooms a man; a prisoner up to new era');
// Output: true

Here we are just making the string to be lowercase and then compare them two.

Congratulations again! You now know how to check after palindromes with Javascript as well!

Alt text of image

Last Remarks

I hope you found this helpful. This is the first part of my “Javascript Algorithms Challenges” series. 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!

Goals

I have many goals this year. The most important one is to become a better developer in general, but also reach 100 followers on Medium and publish more content here that will help others to learn new things. Knowledge is power!

Martin Nordström

Instagram | Twitter | Github

This article was originally posted on Medium. If you want to check it out there, follow this link: Original Article

Discussion

pic
Editor guide
Collapse
thiht profile image
Thibaut Rousseau

The code for isPalindrome is not working, punctuation must be handled

Collapse
zackarnault profile image
Zack Arnault

I just used str = str.toLowerCase().replace(/[a-zA-Z0-9]/ig, ""); to check for special characters and remove them. ^

Collapse
martinnrdstrm profile image
Martin Nordström Author

smart to use regex!!

Collapse
martinnrdstrm profile image
Martin Nordström Author

Oh that's true! I wrote that in repl.it hehe

Collapse
adhonrom profile image
Adhon

can't wait for the next challenge..

Collapse
martinnrdstrm profile image
Collapse
riscie profile image
riscie

Nice one! Where is the next part? ;)

Collapse
martinnrdstrm profile image
Collapse
lalegamero profile image
Alex Gamero

Great one! Thanks a lot for sharing your knowledge and advices with us, Martin.