Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
Uncompress a String, repeat chars `n` times

I have the following problem statement:

Write a function, uncompress, that takes in a string as an argument. The input string will be formatted into multiple groups according to the following pattern:

number + char

for example, '2c' or '3a'.

The function should return an uncompressed version of the string where each 'char' of a group is repeated 'number' times consecutively. You may assume that the input string is well-formed according to the previously mentioned pattern.

test_00: uncompress("2c3a1t"); // -> 'ccaaat'

Here is my code which is using a stack. The problem is that it's only returning 'cc' and I can't figure out why. I've console logged what goes into the IF ELSE and I'm hitting both so I don't understand why nothing gets pushed to the stack.

Would really appreciate the help if someone can spot what I'm missing.

const uncompress = (s) => { 
  const nums = '23456789';
  const stack = []; 
  for (let char of s) {
    if (nums.includes(char)) {
      stack.push(Number(char));
    } else {
      const num = stack.pop();
      stack.push(char.repeat(num));
    };
  };
  return stack.join('');
};

console.log(uncompress("2c3a1t")); // -> 'ccaaat'

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Here's how I would do it:

Split the string up into pairs of numbers and chars:

str.match(/\d+[a-zA-Z]/g)

And reduce that array to a string, while taking each value from the array, getting the char from it (cv.match(/[a-zA-Z]/)[0]) and repeating it according to the number (.repeat(parseInt(cv)))

const uncompress = str => str.match(/\d+[a-zA-Z]/g).reduce((acc, cv) =>
  acc + cv.match(/[a-zA-Z]/)[0].repeat(parseInt(cv)), "")

console.log(uncompress("2c3a1t"))
console.log(uncompress("27b1d8g"))

about 4 years ago · Juan Pablo Isaza Report

0

And just like that I was able to write the code which passed the test case:

  const nums = '123456789';
  const stack = []; 
  for (let char of s) { 
    if (nums.includes(char)) {
      stack.push(Number(char));
    } else {
      let num = '';
      while (nums.includes(stack[stack.length - 1])) {
        num += stack.pop(); 
      }
      stack.push(char.repeat(num));
    };
  };
  return stack.join('');
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!