Solve top-K and string rotation match
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: Solve top-K and string rotation match evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Top-K Largest Elements (Descending)
Constraints
- 0 <= len(nums) <= 10^6
- -10^9 <= nums[i] <= 10^9
- 0 <= k (k may exceed len(nums))
- Duplicates are allowed and preserved in the output
- Return value is sorted in strictly descending order of value
Examples
Input: ([3, 1, 5, 12, 2, 11], 3)
Expected Output: [12, 11, 5]
Explanation: The three largest values are 12, 11, 5, returned in descending order.
Input: ([1, 2, 3, 4, 5], 2)
Expected Output: [5, 4]
Explanation: Already-sorted input; top 2 are 5 and 4.
Hints
- A full sort is O(n log n). Can you avoid sorting the entire array when k is small?
- Maintain a min-heap of size k: the smallest of the k largest sits at the root, so a new element only matters if it beats the root.
- For O(n) average time and O(1) extra space, use quickselect to partition the k-th largest into place, then sort just the top-k slice.
- For very large or streaming inputs you cannot hold in memory, the size-k heap is the right tool — you only ever keep k elements.
String Rotation Match — Minimum Moves
Constraints
- 0 <= len(s), len(goal) <= 10^5
- s and goal consist of lowercase (or arbitrary) characters
- If len(s) != len(goal) the answer is always -1
- Return 0 when s already equals goal
- Return the minimum (smallest) number of moves when multiple rotations match
Examples
Input: ("abcde", "cdeab")
Expected Output: 2
Explanation: After 2 left-rotations 'abcde' -> 'bcdea' -> 'cdeab' equals goal.
Input: ("abcde", "abced")
Expected Output: -1
Explanation: 'abced' is not a rotation of 'abcde', so no number of moves works.
Hints
- Moving the first character to the end i times transforms s into s[i:] + s[:i] — a left rotation by i.
- goal is reachable iff it is a rotation of s. A classic trick: goal is a rotation of s iff goal is a substring of s + s (when lengths are equal).
- The minimum number of moves is the first index i (with i < len(s)) where goal begins inside s + s; use a left-to-right search so you find the smallest i.
- Don't forget the guards: unequal lengths -> -1, identical strings -> 0, and empty strings -> 0.