šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

JS interview question #1: length encoding and decoding for strings

Hi friends! This week I am starting a new section for this blog: hand-picked and fun-to-solve Javascript interview questions. Hope that, with time, this becomes a fun and useful resource to prepare for the algorithmic part of your programming interviews. The first problem is a string encoding one:

šŸ“• Problem
Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character.

For example:

the string "AAAABBBCCDAA" 
would be encoded as "4A3B2C1D2A"

or:

the string "2c1d3e" 
would be encoded as "ccdeee"

Implement the methods for both encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid.

šŸŽ“ Solution (Javascript)
Below is the full code for the solution:

const PLACEHOLDER_CHAR = '#';

const isDigit = (c) => c >= '0' && c <= '9'

const decode = (word) => 
[...word].reduce(
  (decodedWord, char) => 
      decodedWord = isDigit(char) ?
      decodedWord += PLACEHOLDER_CHAR.repeat(Number(char)) :
      decodedWord.replaceAll(PLACEHOLDER_CHAR, char)
  , ''
)

const encode = (word) => {
  let encodedWord = '';
  let counter = 1;
  [...word].forEach((char, index) => {
    if(word.charAt(index + 1) != char) {
      encodedWord+= counter + char;
      counter = 1;
    }
    else {
      counter++;
    }  
  })
  return encodedWord;
}

Example ussage:

console.log(decode('4A3B2C1D2A'));
console.log(encode('AAAABBBCCDAA'));

PS: I've written an article about the javascript array reducer. This is a function that I use quite often when solving these interview questions. Please write me if you have any ideas about how we can improve this.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *