Drill

ProblemsTypeScript › warmup

Rotate a list

mediumwarmupTypeScript

A carousel shows the same items starting from a different one each time it advances.

rotateLeft(values: list<int>, by: int) → list<int>

Solve it in the editor →

Where you start

function rotateLeft(values: number[], by: number): number[] {
  
}

Worked examples

CallResult
rotateLeft([1,2,3,4], 1)[2,3,4,1]
rotateLeft([1,2,3,4], 5)[2,3,4,1]
rotateLeft([1,2,3,4], -1)[4,1,2,3]
rotateLeft([1,2,3], 0)[1,2,3]

Hint

Reduce the shift with a modulo first, and remember that the modulo of a negative number is negative in most of these languages.

Reference solution in TypeScript
function rotateLeft(values: number[], by: number): number[] {
  const n = values.length;
  if (n === 0) return [];
  const k = ((by % n) + n) % n;
  return values.slice(k).concat(values.slice(0, k));
}

The same problem in another language

More warmup problems in TypeScript