Find the number of rotations in a cyclic sequence
I have been given two arrays by user. My code should find out how many
rotations it had either to left or right.
i/p:
array (arr1) 2, 6, 4, 10, 8 ,12 ,11
rotated array(arr2) 4, 10, 8, 12, 11, 2, 6
o/p: 2
Method1:
My approach to this problem would be like this:
1.Take first element from rotated array and also take the last element
from rotated array. Name them "first" and "last" respectively. And also
initialize the count to 0
2.Start comparing "first" with elements of arr1 from the beginning , until
we reach the number "first" in arr1. At the same time start comparing
"last" with elements of arr1 from the end and keep decrementing until we
reach the number equivalent to "last" in arr1.
3.We can do increment and decrement for the step 2 above in the same for
loop for step2.And also increment count variable.
3.Thats it, whichever of "first" or "last" finds its equivalent early then
break and print the count.
Method2:
Take first element of the arr2 and start comparing it with arr1 elements
from the end , and do it until we find a match. The number of times we
decremented the arr1 is equivalent to the number of rotations
Is there any better approach then above two ?
No comments:
Post a Comment