Check if a list is a rotation of another list that works with duplicates
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Checking if one list is a rotation of another is a common computational problem, especially prevalent in fields such as data analysis, cryptography, and computational linguistics. When both lists can contain duplicates, the problem becomes more complex, requiring careful handling to ensure accuracy. In this article, we'll delve into the technical aspects and strategies to determine if a list is a rotation of another list, accommodating duplicates.
Understanding the Problem
A list B is a rotation of another list A if we can shift the elements of A around, wrapping them from end to start, to get B. In mathematical terms, for lists A and B of length n, B is a rotation of A if there exists an i such that for all indices j, B[j] = A[(i + j) % n].
For example, list A = [1, 2, 3, 4] can be rotated to form list B = [3, 4, 1, 2].
However, determining if B is a rotation of A becomes tricky when duplicates are involved. For instance, if A = [1, 2, 2, 3], possible rotations include [2, 2, 3, 1], [2, 3, 1, 2], and [3, 1, 2, 2].
Algorithm Explanation
To check for rotations considering duplicates, there is a neat method that involves the following steps:
- Concatenate List
Awith Itself:- Create a new list
Cthat doublesA. For example, ifA = [1, 2, 2, 3], thenC = [1, 2, 2, 3, 1, 2, 2, 3].
- Check for Subsequence:
- If
Bis indeed a rotation ofA, it should appear as a contiguous subsequence withinC.
- Utilize String Matching:
- Transform both
AandBinto strings and use a string-matching algorithm to check ifBexists inC. This can be achieved using simple methods like Python'sinoperator or more advanced string-matching algorithms such as Knuth-Morris-Pratt (KMP) for better efficiency.
Example Implementation
Here's a Python function that implements the above approach:
- Different Length Lists: If
AandBhave different lengths,Bcannot be a rotation ofA. - Empty Lists: By definition, an empty list is trivially a rotation of itself.
- All-identical Elements: Special case handling is not required as the method works uniformly.
- Time Complexity: The primary cost is in the subsequence check. On average, it runs in , where
nis the length of the list, using efficient string matching. - Space Complexity: We construct
C, doubling the size ofA, leading to additional space.

