Problem 189

Abstract / Summary

Given an array and a number of steps rotate the array elements to the right by that many steps in place.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0189.cpp

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        k %= nums.size();
        k = nums.size() - k;
        std::rotate(nums.begin(), nums.begin() + k, nums.end());
    }
};
8 lines | 206 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (9+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Math
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single public method rotate. The method receives a mutable reference to a std::vector<int> and an integer k. Its purpose is to rotate the elements of the vector to the right by k positions, wrapping elements that fall off the end back to the front. The algorithm leverages the C++ Standard Library to achieve the rotation efficiently while handling a variety of input conditions.

Key Steps

The rotation logic is composed of three distinct operations, each reflected in a concise code fragment.

The first operation normalizes the rotation count with respect to the vector length:

k %= nums.size();

By applying the modulo operator, any k that exceeds the number of elements is reduced to an equivalent smaller offset. This ensures that the subsequent steps work with the minimal necessary shift.

The second operation converts the right-rotation problem into a left-rotation that std::rotate can handle directly. The transformation is performed by subtracting the normalized k from the vector size:

k = nums.size() - k;

When k is zero after the modulo, the subtraction yields the original size, which std::rotate interprets as a no-op. For any other value, the computed index points to the element that should become the new first element after rotation.

The final step invokes the standard algorithm std::rotate, supplying iterators that delineate the range to be rotated and the pivot position:

std::rotate(nums.begin(), nums.begin() + k, nums.end());

std::rotate rearranges the elements in-place, moving the segment [nums.begin(), nums.begin() + k) to the end while preserving the relative order of all elements.

Edge Cases Handled

When k is a multiple of the vector length, the modulo operation reduces k to zero. The subsequent subtraction yields a pivot equal to the vector size, causing std::rotate to receive a range where the middle iterator coincides with the end iterator. In this situation the algorithm performs no modifications, effectively leaving the vector unchanged.

If k is zero from the outset, the modulo step leaves it unchanged, and the subtraction produces a pivot equal to the vector size. The call to std::rotate again results in a no-op, confirming that the method gracefully handles a request for zero rotation.

For vectors containing a single element, the size is one. The modulo operation yields zero regardless of k, and the subtraction produces a pivot of one. std::rotate receives a range where the middle iterator is the end iterator, which again leads to no movement, correctly preserving the sole element.

The code also implicitly supports negative values of k if they are supplied, because the modulo operation with a negative dividend yields a negative remainder in C++. The subsequent subtraction still computes a valid pivot within the range [0, size], allowing std::rotate to perform the appropriate leftward shift that corresponds to a rightward rotation by a negative offset.

Performance Optimizations

The implementation minimizes work by reducing the rotation count with a modulo operation, eliminating unnecessary full-cycle rotations. This early reduction prevents the algorithm from traversing the vector more times than required.

By delegating the core rearrangement to std::rotate, the method benefits from the highly tuned library implementation, which typically employs a three-reverse technique or block swapping to achieve the rotation with a minimal number of element moves. This in-place strategy avoids allocating auxiliary storage, keeping the memory footprint low.

The use of iterator arithmetic (nums.begin() + k) provides direct access to the pivot position without additional loops or index calculations, allowing the compiler to generate efficient pointer arithmetic.

Overall, the combination of input normalization, transformation to a left-rotation, and reliance on a standard library routine results in a concise solution that executes with optimal data movement and low overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long line of numbered toy blocks sitting in a row. Sometimes you want to shift these blocks so that the ones at the end move to the front, just like a spinning merry-go-round.

The first part of this code finds out exactly how many blocks need to move. If you have a very long line of blocks and you want to jump them forward a huge number of times, it figures out the shorter way to get them to the same spots.

Next, the code figures out the new starting point for the line. It counts backward from the end of the row to find the perfect spot where the shift should happen.

Finally, the computer uses a special command to shuffle the blocks around. It takes the group of blocks starting from that new spot and moves them to the very front of the line, while pushing the other blocks neatly out of the way to the back. Every block stays in its same relative order, but they have all slid over to take their new places in the row.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.50 | σ = 1.01

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python C# Rust JS Go TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JS
fartem Ruby
FelixFan1122 C#
fpdjsns C++
fsq C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
pruthvikp Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vthwang Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fpdjsns C++
fsq C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
pruthvikp Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vthwang Java
56 links | 39 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Rotate Array | Leetcode 189 | Top 150 interview question series'
Technosage 12 mins
Rotate Array | Leetcode 189 | Top 150 interview question series
YouTube video '9. Rotate array | Arrays - Easy | Learn DSA | Leetcode 189'
Ayushi Sharma 9 mins
9. Rotate array | Arrays - Easy | Learn DSA | Leetcode 189
YouTube video 'LeetCode 189: Rotate Array - Interview Prep Ep 52'
Fisher Coder 20 mins
LeetCode 189: Rotate Array - Interview Prep Ep 52
YouTube video 'rotate array | rotate array leetcode | leetcode 189 | 2 solutions'
Naresh Gupta 9 mins
rotate array | rotate array leetcode | leetcode 189 | 2 solutions
YouTube video 'LeetCode 189 | Rotate Array Solution Visually Explained | Top Interview 150 |'
ByteQuest 3 mins
LeetCode 189 | Rotate Array Solution Visually Explained | Top Interview 150 |
YouTube video 'Leetcode | 189. Rotate Array | Medium | Java Solution [2 Methods - O(1) Space]'
Developer Docs 11 mins
Leetcode | 189. Rotate Array | Medium | Java Solution [2 Methods - O(1) Space]
YouTube video 'Rotate Array | Leet code 189 | Theory explained + Python code'
Sai Anish Malla 12 mins
Rotate Array | Leet code 189 | Theory explained + Python code
YouTube video '189  Rotate Array | Zero to FAANG Kunal | Assignment Solution | Leetcode'
Programmers Zone 30 mins
189 Rotate Array | Zero to FAANG Kunal | Assignment Solution | Leetcode
YouTube video 'LeetCode 189: Rotate Array | C# Solution | Multiple Approaches |'
Code Scribbler 8 mins
LeetCode 189: Rotate Array | C# Solution | Multiple Approaches |
YouTube video 'LeetCode 189: Rotate Array | C# Solution | In-Place Manipulation'
Code Scribbler 6 mins
LeetCode 189: Rotate Array | C# Solution | In-Place Manipulation
YouTube video 'Rotate Array | Leetcode 189 | Arrays | O(n) Time Complexity #dsa #leetcode'
Learn With Chirag 9 mins
Rotate Array | Leetcode 189 | Arrays | O(n) Time Complexity #dsa #leetcode
YouTube video 'Rotate Array - Leetcode 189 - In-Place - JavaScript Solution Explained'
Web Coder Abhishek 7 mins
Rotate Array - Leetcode 189 - In-Place - JavaScript Solution Explained
YouTube video 'Rotate Array | Leeetcode 189  | Live coding session  🔥🔥🔥 | 2 Solutions SC O(1)/O(n) | TC O(n)'
Coding Decoded 7 mins
Rotate Array | Leeetcode 189 | Live coding session 🔥🔥🔥 | 2 Solutions SC O(1)/O(n) | TC O(n)
YouTube video 'Leetcode 189 - Rotate Array (JAVA Solution Explained!)'
LC Bear 6 mins
Leetcode 189 - Rotate Array (JAVA Solution Explained!)
YouTube video 'Leetcode | Top Interview 150 | Easy | 189. Rotate Array | Time: O(N).N | Javascript'
Software Interviews Prep 10 mins
Leetcode | Top Interview 150 | Easy | 189. Rotate Array | Time: O(N).N | Javascript
YouTube video '189. Rotate Array | Leetcode | Arrays | Fundamentals'
Coding with Tamilarasan 9 mins
189. Rotate Array | Leetcode | Arrays | Fundamentals
YouTube video 'Daily Leetcode #670: Jan 30, 2022 - 189. Rotate Array'
Programming Live with Larry 12 mins
Daily Leetcode #670: Jan 30, 2022 - 189. Rotate Array
YouTube video 'Daily Leetcode #198: Oct 15, 2020 - 189. Rotate Array'
Programming Live with Larry 21 mins
Daily Leetcode #198: Oct 15, 2020 - 189. Rotate Array
YouTube video 'Day 186: LeetCode Problem 189. Rotate Array - Swift'
iOSxBank 11 mins
Day 186: LeetCode Problem 189. Rotate Array - Swift
YouTube video '189. Rotate Array | Leetcode | Python'
Abdullah Arshed 5 mins
189. Rotate Array | Leetcode | Python
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality