Rotate Array
You get an array of numbers and a number k. Shift the array k places to the right in a circle: the numbers that fall off the end come back at the start. Do it inside the same array, without a second one. Our example: [1, 2, 3, 4, 5, 6], k = 2 → [5, 6, 1, 2, 3, 4].
- input
nums: integers;k: how many steps to turn them by.- returns
- Nothing: turn
numsin placeksteps to the right, so that the last number moves to the frontktimes over.kmay be larger than the length. - constraints
- 1 ≤ nums.length ≤ 10⁴
- −2³¹ ≤ nums[i] ≤ 2³¹ − 1
- 0 ≤ k ≤ 10⁵
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
function rotate(nums, k) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more two pointers problems
- 125Valid PalindromeEasysolve
- 26Remove Duplicates from Sorted ArrayEasysolve
- 283Move ZeroesEasysolve
- 88Merge Sorted ArrayEasysolve
- 27Remove ElementEasysolve
- 392Is SubsequenceEasysolve
- 167Two Sum II - Input Array Is SortedMediumsolve
- 153SumMediumsolve
- 11Container With Most WaterMediumsolve
- 80Remove Duplicates from Sorted Array IIMediumsolve
- 151Reverse Words in a StringMediumsolve
- 5Longest Palindromic SubstringMediumsolve
- 42Trapping Rain WaterHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.