Fácil 0 resolvidos 0% de aceitação

Rotate Array

Rotate a list to the right by some steps.

O que você vai aprender

  • Shift elements with index arithmetic
  • Reduce large rotations with modulo
  • Build a rotated copy of a list

Problema

Ver tradução

Rotate the list to the right by steps positions: the last element moves to the front, steps times.

Implement rotate_right(numbers, steps).

Input

numbers: The list of integers. steps: How many positions to rotate.

Output

Return the rotated list.

Restrições

0 ≤ length ≤ 100,000; 0 ≤ steps ≤ 10⁹

Exemplos

Exemplo 1
Entrada:
numbers = [1, 2, 3, 4, 5]
steps = 2

Saída esperada:
expected = [4, 5, 1, 2, 3]
Entrada:
std::vector<long long> numbers = {1, 2, 3, 4, 5};
long long steps = 2;

Saída esperada:
std::vector<long long> expected = {4, 5, 1, 2, 3};
Entrada:
long[] numbers = new long[] {1, 2, 3, 4, 5};
long steps = 2;

Saída esperada:
long[] expected = new long[] {4, 5, 1, 2, 3};

Explicação

Two right rotations: [5, 1, 2, 3, 4], then [4, 5, 1, 2, 3].

Exemplo 2
Entrada:
numbers = [1, 2, 3]
steps = 3

Saída esperada:
expected = [1, 2, 3]
Entrada:
std::vector<long long> numbers = {1, 2, 3};
long long steps = 3;

Saída esperada:
std::vector<long long> expected = {1, 2, 3};
Entrada:
long[] numbers = new long[] {1, 2, 3};
long steps = 3;

Saída esperada:
long[] expected = new long[] {1, 2, 3};

Explicação

Rotating by the length brings the list back: [1, 2, 3].

Como abordar

Tente sozinho primeiro e depois abra uma dica de cada vez.

Dica 1

A rotation by the list length changes nothing, so only the remainder matters.

Dica 2

Think of splitting the list near the end and moving that tail to the front.

Dica 3

Handle very large step counts by reducing them before rearranging.

Complexidade esperada

O(n) time, O(n) extra space

Referências

Este desafio foi adaptado para o CodeUtility. Siga o enunciado e as restrições acima.

A melhor solução aprovada de cada programador. As mais rápidas, leves e mais bem avaliadas ficam no topo.

Ainda não há soluções aprovadas. Resolva e fique com o primeiro lugar.

Aprenda com outros

Soluções da comunidade

Ainda não há soluções publicadas. Resolva este desafio para compartilhar a primeira.