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?- A. acbdcb abcbdc aaabb
- B. abcdcb acbdcb aaabb
- C. acbdcb acbdcb aabba
- 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
- Problem: Compute the bitwise AND of every integer in [m, n] in O(log n): it is the common binary prefix of m and n followed by zeros…
- Problem: Count the total number of 1 bits in all integers from 0 to n without iterating over them: bit b repeats a pattern of 2^b zeros…
- Problem: Minimum single-bit flips in a and b so that (a OR b) == c. python def minflips(a, b, c): flips = 0 while a or b or c: x, y, z = a…
- Problem: Euler's totient φ(n) counts integers in 1..n coprime to n: φ(n) = n · Π (1 − 1/p) over distinct primes p dividing n, computed by…
- Problem: Find the maximum product len(w1) · len(w2) over pairs of words that share no letter, using a 26-bit letter mask per word. python…
- Problem: Sum (a[i] XOR a[j]) over all pairs i < j in O(n · bits): at bit b, a pair contributes 2^b exactly when one value has the bit and…