My code is too slow

What is the issue:
CodeWars is not accepting my solution and I’m assuming it’s because my code is too slow? If that’s the case please help me think about how to make it faster. Thank you!

My code so far:

function revrot(str, sz) {
  let chunks = [];
  const cutAmount = Math.floor(str.length / sz)
  let cut = 0;
  while (cut != cutAmount) {
    chunks.push(str.slice(cut * sz, sz * (cut + 1)))
    cut++;
  }
  for (let i=0;i<chunks.length;i++){
    const isDivBy2 = chunks[i]
      .split('')
      .map(num => Math.pow(num, 3))
      .reduce((acc, num) => acc + num, 0)
    if (isDivBy2 % 2 === 0) {
      chunks[i] = chunks[i].split('').reverse().join('')
    }
    chunks[i] = chunks[i].slice(1) + chunks[i][0]
  }
  return chunks.join('')
}

revrot("123456987654", 6)
// -> "234561876549"

Link to the challenge:
Reverse or rotate?

Part of the problem lies in the following three lines:

  const cutAmount = Math.floor(str.length / sz)
  let cut = 0;
  while (cut != cutAmount) {

If the value 0 is passed as sz, what do you think will happen?

1 Like

You definitely need to fix the early exit conditions first for correctness:

sz is <= 0 or if str is empty return “”

But you can speed up your code by

  • not making an array of chunks

  • not taking the cube (do you need to take the cube to know if the sum of the cubes is even or odd?)

1 Like