Created
May 9, 2022 07:42
-
-
Save Josephchinedu/371df7559dd5f36d7987bfa919f88359 to your computer and use it in GitHub Desktop.
rotate array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Given an array, rotate the array to the right by k steps, where k is non-negative. | |
example, we're give an array [1,2,3,4,5,6,7] and we want to rotate it by 3 times | |
nums = [1,2,3,4,5,6,7] | |
k = 3 | |
we're going to modulo the k element, just incase the k element is more than the length of our array. | |
k = k % len(array) | |
we're going to solve this using using "O(1)" time complexity. | |
we're going to rotate the array, that means we've have two portion, the one that will be moved to right: [1234], and another portion | |
that we'll move to left: [567] because it's the last K element. | |
first, we'll reverse the entire array, our result will be | |
[7, 6, 5, 4, 3, 2, 1] | |
the above array is not our expected result, so, we'll reverse the k element which is [7,6,5] | |
and also reverse the other part [3,2,1] to be able to get our expected result. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment