Initial array: 2 23 34 27 89 14 26 30 60
k = 3
starting from index i = 1 we have to shift k elements so that they occur after the element 26 (i.e. after givenIndex = 6) in the array.
Final array: 2 89 14 26 23 34 27 30 60
We are NOT allowed to use extra space.
My approach:
count = 0;
while(count < k)
{
count++;
temp = arr[i];
shift all elements from (i+1) to givenIndex to their immediate left position;
arr[givenIndex] = temp;
}
First iteration:
temp = 23
shift all elements from [i+1](i.e. index=2) to givenIndex(i.e. index=6) to left one by one
array after shifting: 2 34 27 89 14 26 26 30 60
arr[givenIndex] = temp
array after applying this operation: 2 34 27 89 14 26 23 30 60
Similarly
array after second iteration: 2 27 89 14 26 23 34 30 60
array after third iteration: 2 89 14 26 23 34 27 30 60
worst case complexity O(n*k) where n is the no. of elemnts in the array.
Can we solve the problem in O(n)