Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Find the lexicographically smallest rotation of a string in O(n) with a two-candidate comparison (Booth-style), and compare it with the O(n²) brute force.

Problem: Find the lexicographically smallest rotation of a string in O(n) with a two-candidate comparison (Booth-style), and compare it with the O(n²) brute force.
def min_rot(s):
    n = len(s); ss = s + s; i, j, k = 0, 1, 0
    while i < n and j < n and k < n:
        a, b = ss[i + k], ss[j + k]
        if a == b: k += 1; continue
        if a > b: i += k + 1
        else: j += k + 1
        if i == j: j += 1
        k = 0
    st = min(i, j)
    return ss[st:st + n]
print(min_rot("dcbacb"), min(("dcbacb"[i:] + "dcbacb"[:i]) for i in range(6)), min_rot("baaab"))
What is printed?
  1. A. acbdcb abcbdc aaabb
  2. B. abcdcb acbdcb aaabb
  3. C. acbdcb acbdcb aabba
  4. D. acbdcb acbdcb aaabb

Correct answer: D. acbdcb acbdcb aaabb

i and j are candidate starts; when they first differ at offset k, the candidate with the larger character cannot be the answer, nor can any start within the next k positions after it (they are dominated by the matching suffix of the other). Rotations of "dcbacb": dcbacb, cbacbd, bacbdc, acbdcb, cbdcba, bdcbac → "acbdcb". "baaab" → "aaabb". Sorting the characters ("abbccd") is not a rotation. O(n).

More Coding Interview Problems questions

Exams that ask this topic