Calculate String Rotation

Approach

  1. if swhiftedWord is same with targetWord return process repeat count

  2. if count is over than shiftedWord return -1 because that means it's already roatat one cycle but didn't match with targetWord

  3. if passed process-1, process-2 go back to process-1 with one shifted to the right word with increased count

Solution

const shiftedDiff = (first, second, count = 0) => {
  if (first === second) {
    return count;
  }
  if (count > first.length) {
    return -1;
  }
  
  return shiftedDiff(first[first.length - 1] + first.slice(0, first.length - 1), second, count + 1);
};

Last updated

Was this helpful?