BackmediumArraysRazorpay

Galactic Vessel Alignment Solution

Problem Statement

Given two integer arrays A and B of the same length, determine whether B can be transformed into A by performing a series of cyclic right rotations. A single right rotation moves the last element of the array to the front, shifting all other elements one position to the right. If such a transformation is possible, output the minimum number of right rotations required; otherwise output -1. The input consists of an integer n (the length of the arrays), followed by a line with n space‑separated integers representing A, and a line with n space‑separated integers representing B. The output is a single integer as described.

Example 1
Input
5 1 2 3 4 5 3 4 5 1 2
Output
2

Explanation: Rotating B right once yields [2,3,4,5,1]; rotating again yields [1,2,3,4,5] which matches A. No fewer rotations achieve equality, so the answer is 2.

Example 2
Input
4 7 8 9 10 10 7 8 9
Output
1

Explanation: A single right rotation moves the last element 9 to the front, producing [9,10,7,8]; a second rotation gives [8,9,10,7]; a third gives [7,8,9,10] which equals A. The minimal number of rotations is 3, but rotating left once is equivalent to three right rotations. Since we count right rotations, the answer is 3.

Example 3
Input
3 5 5 5 5 5 5
Output
0

Explanation: Both arrays are already identical; zero rotations are needed.

Constraints

  • 1 <= n <= 100000
  • -10^9 <= A[i], B[i] <= 10^9
  • All elements are integers
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Galactic Vessel Alignment — Problem Statement & Solution Guide

ArraysMediumpattern recognition and rotation
TimeO(n)
|
SpaceO(n)

Problem Description

Given two integer arrays A and B of the same length, determine whether B can be transformed into A by performing a series of cyclic right rotations. A single right rotation moves the last element of the array to the front, shifting all other elements one position to the right. If such a transformation is possible, output the minimum number of right rotations required; otherwise output -1. The input consists of an integer n (the length of the arrays), followed by a line with n space‑separated integers representing A, and a line with n space‑separated integers representing B. The output is a single integer as described.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Galactic Vessel Alignment"

medium

WHY DOES IT MATTER?

Detecting cyclic equivalence appears in string matching, networking packet reassembly, and circular buffer management; mastering the B+B pattern equips engineers to solve a broad class of rotation‑related problems efficiently.

OPTIMIZATION CHALLENGE

The key insight is that all rotations of B are linearly represented in B+B, turning a combinatorial search into a single linear substring search, thereby collapsing O(n^2) possibilities into O(n) work.

REAL-WORLD CONNECTION

Consider a distributed log that is replicated in a ring topology; verifying that two replicas contain the same sequence of events despite different starting points is exactly a rotation check, analogous to matching B+B against A.

In an interview, first state the B+B observation, then immediately mention KMP (or built‑in index) to achieve linear time; avoid writing nested loops that hint at quadratic complexity.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(n)

Core Theory — Why This Approach?

The problem reduces to checking whether one array is a cyclic rotation of another. A naive element‑by‑element comparison for each possible shift leads to O(n^2) time, which quickly becomes infeasible for large n (e.g., n≈10^5). The optimal paradigm treats the rotation check as a substring search: by concatenating array B with itself (B+B) we embed every possible rotation of B as a contiguous sub‑array of length n. The task then becomes finding A as a sub‑array inside B+B, which can be solved in linear time using a string‑matching algorithm such as Knuth‑Morris‑Pratt (KMP) or Rabin‑Karp. Once the starting index i of the match is known, the required right rotations are (n‑i) mod n, giving the minimal count because any further full cycles would repeat the same configuration. This approach guarantees O(n) time and O(n) auxiliary space for the failure function, dramatically improving over the quadratic brute force.

Interview Questions on This Problem

Q1How would you determine if array B can be transformed into A using only cyclic right rotations, and compute the minimal number of rotations?

Concatenate B with itself to form C = B+B. Use KMP to search for A as a sub‑array of C within the first n positions. If found at index i, the minimal right rotations = (n‑i)%n; otherwise return -1.

Q2Why is the "B+B" trick valid for rotation detection, and does it work for both left and right rotations?

Because rotating B left by i positions yields the sub‑array C[i..i+n‑1] in B+B. A right rotation by k is equivalent to a left rotation by n‑k, so the same trick captures both directions; the index i gives the left shift, from which the right shift is derived.

Q3What are the time and space complexities of using KMP for this problem compared to using a hash‑based rolling checksum like Rabin‑Karp?

Both KMP and Rabin‑Karp run in O(n) expected time; KMP guarantees O(n) worst‑case time with O(n) extra space for the prefix table, while Rabin‑Karp uses O(1) extra space but may suffer collisions, leading to occasional O(n^2) worst‑case behavior.

Examples

Example 1

Input

5
1 2 3 4 5
3 4 5 1 2

Output

2

Explanation: Rotating B right once yields [2,3,4,5,1]; rotating again yields [1,2,3,4,5] which matches A. No fewer rotations achieve equality, so the answer is 2.

Example 2

Input

4
7 8 9 10
10 7 8 9

Output

1

Explanation: A single right rotation moves the last element 9 to the front, producing [9,10,7,8]; a second rotation gives [8,9,10,7]; a third gives [7,8,9,10] which equals A. The minimal number of rotations is 3, but rotating left once is equivalent to three right rotations. Since we count right rotations, the answer is 3.

Example 3

Input

3
5 5 5
5 5 5

Output

0

Explanation: Both arrays are already identical; zero rotations are needed.

Constraints

  • 1 <= n <= 100000
  • -10^9 <= A[i], B[i] <= 10^9
  • All elements are integers

Optimal Approach & Strategy

Concatenate B with itself and run a linear‑time substring search (KMP) to locate A, then compute rotations from the match index.

Brute Force Approach

Try every possible rotation (0 to n‑1) and compare the whole array each time, leading to O(n^2) time.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function buildLPS(pat){
    const m=pat.length;
    const lps=new Array(m).fill(0);
    let len=0,i=1;
    while(i<m){
        if(pat[i]===pat[len]){len++; lps[i]=len; i++;}
        else if(len) len=lps[len-1];
        else {lps[i]=0; i++;}
    }
    return lps;
}
function minRotations(A,B){
    const n=A.length;
    if(n!==B.length) return -1;
    if(n===0) return 0;
    const text=new Array(2*n);
    for(let i=0;i<2*n;i++) text[i]=B[i%n];
    const lps=buildLPS(A);
    let i=0,j=0;
    while(i<2*n){
        if(text[i]===A[j]){i++;j++; if(j===n){const pos=i-j; if(pos<n){return (n-pos)%n;} j=lps[j-1];}}
        else if(j) j=lps[j-1];
        else i++;
    }
    return -1;
}
const fs=require('fs');
const data=fs.readFileSync(0,'utf8').trim().split(/\s+/).map(Number);
let p=0; const n=data[p++]||0; const A=data.slice(p,p+n); p+=n; const B=data.slice(p,p+n);
console.log(minRotations(A,B).toString());

Asked in Top Tech Interviews

Razorpay

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.