Data Structures & AlgorithmsHardGATE CS · TCS NQT
To test whether string s2 is a rotation of string s1 in linear time, which approach is standard?
- A. Sort both strings and compare
- B. Compare every rotation of s1 with s2 by brute force
- C. Build a suffix tree of s1 only
- D. Search for s2 inside s1 concatenated with itself, using KMP or Z-function
Correct answer: D. Search for s2 inside s1 concatenated with itself, using KMP or Z-function
Every rotation of s1 is a substring of s1 + s1 of length |s1|, so a linear-time pattern matcher finds it. Sorting detects anagrams, not rotations.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- For each element of an array of distinct integers, the task is to count how many earlier elements are smaller. Which structure achieves…
- What is the length of the longest common subsequence of the three strings "ABCBDAB", "BDCABA" and "BCADB"?
- How many non-empty subsequences of "abcbab" (chosen by index, so the same letters at different positions count as different subsequences)…
- How many index triples i < j < k in [3, 1, 4, 1, 5, 9, 2, 6] satisfy a[i] < a[j] < a[k] (strictly increasing)?
- You stand on index 0 and must reach index 7. From index i you may move to any of the next 2 indices (i+1 or i+2). Landing on index j costs…
- What is the maximum product of THREE distinct elements of [-10, -3, 1, 5, 2, -8, 4] (chosen by position)?