GeeksforGeeks » Algorithms

Find the extent of rotation

(8 posts)
  1. kamal
    guest
    Posted 1 year ago #

    suppose you've two arrays arr1[N] and arr2[N] of integers. 'arr2' is cyclic right rotated version of arr1 by some unknown places 'k'. where it's known that 1 <= k <= N. you've to determine 'k'.

    example-

    arr1 = 1, 2, 3, 4, 5

    arr2 = 3, 4, 5, 1, 2

    you see, if you rotate right (cyclic) to arr1 by 3 places (thus, here, k == 3) then you'll find arr2. thus arr2 is cyclic right rotated (by 3 places) version of arr1.

    complexities requirements-

    time: O(N)
    space: O(N). (can you still reduce space complexity? )

  2. kewl_coder
    Member
    Posted 1 year ago #

    I suppose I have not understood the problem correctly.In my opinion, we can do it in O(n) without any space complexity(apart from that of the two arrays ) .
    keep searching for arr2[0] in arr1[] and when you find it, compare arr2's next & previous with those of arr1's.

    Please correct where I am wrong.

  3. kapil
    guest
    Posted 1 year ago #

    It won't be that easyy if there r duplicates

  4. Nanu
    guest
    Posted 12 months ago #

    Double the rotated string. Check if the original string is a substring of the doubled string. If it is then start index of that substring is the index of rotation

  5. ish7
    guest
    Posted 11 months ago #

    I guess... It can be done in log n time.. take the element in the starting index of the rotated array... now find the index of that element in the original array through binary search let it be i.. then the extent of rotation of the rightly rotated array shall be (n-i), where n corresponds to the total number of elements in the array...
    Correct me if I m wrong...

  6. Nanu
    guest
    Posted 11 months ago #

    Solution provided above would work only for ordered arrays. Also it is flawed in the case of duplicate elements

  7. sankalp
    guest
    Posted 11 months ago #

    There are two approaches to do this ,
    1)Just append the rotated array to itself and search in it for the first array .This will be a simple KMP based pattern search and will take O(n) time and O(n) space for building auxiliary array .

    2)Find any unique element in the first array
    IF there is no unique element
    else , find the element which is repeated for times < sizeof(array)
    Find this element
    If it is unique , return we can calculate the extent of rotation as abs(index in array1 -index in array2 +1)

    else ,
    If it is repeated , this approach can again be used to find the answer but logic will be complex

    it is O(n) time and O(1) space

  8. jpchaandy
    Member
    Posted 10 months ago #

    u can do easily in o(n^2)


Reply

You must log in to post.

RSS feed for this topic