Tutte le sfide
Facile 0 risolte 0% di accettazione

Rotate Array

Rotate a list to the right by some steps.

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

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

Esempi

Esempio 1
Input:
numbers = [1, 2, 3, 4, 5]
steps = 2

Output atteso:
expected = [4, 5, 1, 2, 3]
Input:
std::vector<long long> numbers = {1, 2, 3, 4, 5};
long long steps = 2;

Output atteso:
std::vector<long long> expected = {4, 5, 1, 2, 3};
Input:
long[] numbers = new long[] {1, 2, 3, 4, 5};
long steps = 2;

Output atteso:
long[] expected = new long[] {4, 5, 1, 2, 3};

Spiegazione

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

Esempio 2
Input:
numbers = [1, 2, 3]
steps = 3

Output atteso:
expected = [1, 2, 3]
Input:
std::vector<long long> numbers = {1, 2, 3};
long long steps = 3;

Output atteso:
std::vector<long long> expected = {1, 2, 3};
Input:
long[] numbers = new long[] {1, 2, 3};
long steps = 3;

Output atteso:
long[] expected = new long[] {1, 2, 3};

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

Handle very large step counts by reducing them before rearranging.

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.