Back to Freecodecamp

Challenge 119: String Compression

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f04.md

latest1.6 KB
Original Source

--description--

Given a string sentence, return a compressed version of the sentence where consecutive duplicate words are replaced by the word followed with the number of times it repeats in parentheses.

  • Only consecutive duplicates are compressed.
  • Words are separated by single spaces.

For example, given "yes yes yes please", return "yes(3) please".

--hints--

compressString("yes yes yes please") should return "yes(3) please".

js
assert.equal(compressString("yes yes yes please"), "yes(3) please");

compressString("I have have have apples") should return "I have(3) apples".

js
assert.equal(compressString("I have have have apples"), "I have(3) apples");

compressString("one one three and to the the the the") should return "one(2) three and to the(4)".

js
assert.equal(compressString("one one three and to the the the the"), "one(2) three and to the(4)");

compressString("route route route route route route tee tee tee tee tee tee") should return "route(6) tee(6)".

js
assert.equal(compressString("route route route route route route tee tee tee tee tee tee"), "route(6) tee(6)");

--seed--

--seed-contents--

js
function compressString(sentence) {

  return sentence;
}

--solutions--

js
function compressString(sentence) {
  const words = sentence.split(" ");
  const result = [];
  let count = 1;

  for (let i = 0; i < words.length; i++) {
    if (words[i] === words[i + 1]) {
      count++;
    } else {
      if (count > 1) {
        result.push(`${words[i]}(${count})`);
      } else {
        result.push(words[i]);
      }
      count = 1;
    }
  }

  return result.join(" ");
}