list rotation
duplicates in list
list comparison
algorithm
data structures

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:

  1. Concatenate List A with Itself:
    • Create a new list C that doubles A. For example, if A = [1, 2, 2, 3], then C = [1, 2, 2, 3, 1, 2, 2, 3].
  2. Check for Subsequence:
    • If B is indeed a rotation of A, it should appear as a contiguous subsequence within C.
  3. Utilize String Matching:
    • Transform both A and B into strings and use a string-matching algorithm to check if B exists in C. This can be achieved using simple methods like Python's in operator 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 A and B have different lengths, B cannot be a rotation of A.
  • 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 O(n)O(n), where n is the length of the list, using efficient string matching.
  • Space Complexity: We construct C, doubling the size of A, leading to O(n)O(n) additional space.

Course illustration
Course illustration

All Rights Reserved.