![]() |
VOOZH | about |
Given an array b. The array b is obtained initially by array a, by doing the following operations.
Fixed point x is that point where (a[i] = i ). These operations are performed on the array a k times, determine if you will be able to restore the array a given array b.
Examples:
Input : n = 5 , k = 3 , b = { 4,3, 3, 2, 3 }
Output: Yes
Explanation: The array 'a' was initially given as [3, 2, 3, 4, 3]. In the first operation, a specific position, denoted as x=2, was selected. After performing 2 left shifts at this position, the array transformed into [3, 4, 3, 3, 2]. For the second operation, a different fixed point x=3 was chosen, and executing 3 left shifts resulted in the array [3, 2, 3, 4, 3]. Subsequently, in the third operation, the same fixed point x=3 was selected, and after 3 left shifts, the array transformed into [4, 3, 3, 2, 3]. Notably, this final array is equivalent to the array 'b'.Input : n = 5 , k = 5 , b = { 6, 1, 1, 1, 1 }
Output : No
Explanation : the size of the array is 5 and we are given with 6 as our array element, and our condition specifically says a[i] = i , hence 6 can never satisfy our condition for the cyclic rotation of array.
Approach:
The Idea here is that the last element will always be the one which was our fixed point one step before and now is at the last because we cyclically rotated the array towards left which results in the fixed point array element being at the last of the array. If we try to right rotate the array k times then we will surely be getting our original array a, but if we found and element at the end whose value is greater then the size of the array , then we stop and report that we cannot generate our array a, else we continue right shifting k times. Since right shifting can be a time consuming task we just shift the last index pointer in our array, and % remainder modulus it so that it does not goes out of bounds from the indexes.
Follow the steps to solve the above problem:
lastindex to the index of the last element in the array 'b'.min(n, k) times. lastindex is greater than n. If true, set the flag to false and break out of the loop.lastindex to a new position based on the current element and update lastindex accordingly, moving the calculated distance steps clockwise in the array.Below is the implementation of above approach:
Yes
Time Complexity : O(n), where n is the length of the array.
Auxiliary space : O(1).