Solve palindrome and list tasks
Company: Reddit
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in string algorithms and linked list manipulation, specifically techniques for constructing the shortest palindrome by prepending characters and reordering singly linked lists by 1-based index parity.
Part 1: Build the shortest palindrome by prepending characters
Constraints
- 0 <= len(s) <= 100000
- s consists of lowercase English letters
Examples
Input: "aacecaaa"
Expected Output: "aaacecaaa"
Explanation: The longest palindromic prefix is "aacecaa", so only "a" must be added to the front.
Input: "abcd"
Expected Output: "dcbabcd"
Explanation: Only the first character is a palindromic prefix, so prepend the reverse of "bcd", which is "dcb".
Input: ""
Expected Output: ""
Explanation: The empty string is already a palindrome.
Input: "a"
Expected Output: "a"
Explanation: A single character is already a palindrome.
Input: "aaaa"
Expected Output: "aaaa"
Explanation: The entire string is already a palindrome, so nothing needs to be added.
Input: "abbacd"
Expected Output: "dcabbacd"
Explanation: The longest palindromic prefix is "abba". The remaining suffix is "cd", so prepend its reverse, "dc".
Hints
- The key is to find the longest prefix of s that is already a palindrome.
- Try building a pattern from s and reversed(s), then use a prefix-function such as KMP to find the overlap efficiently.
Part 2: Reorder a linked list by index parity
Constraints
- 0 <= n <= 100000, where n is the number of nodes
- Each node value fits in a 32-bit signed integer
Examples
Input: [1, 2, 3, 4, 5]
Expected Output: [1, 3, 5, 2, 4]
Explanation: Values at odd 1-based positions are 1, 3, and 5. Values at even positions are 2 and 4.
Input: [2, 1, 3, 5, 6, 4, 7]
Expected Output: [2, 3, 6, 7, 1, 5, 4]
Explanation: Odd-positioned values are 2, 3, 6, 7. Even-positioned values are 1, 5, 4.
Input: []
Expected Output: []
Explanation: An empty list remains empty.
Input: [10]
Expected Output: [10]
Explanation: A single node is already correctly ordered.
Input: [4, 4, 4, 4]
Expected Output: [4, 4, 4, 4]
Explanation: Odd-positioned values are [4, 4] and even-positioned values are [4, 4], so the final list looks the same.
Input: [-1, -2, -3, -4, -5, -6]
Expected Output: [-1, -3, -5, -2, -4, -6]
Explanation: Odd-positioned values are -1, -3, -5 and even-positioned values are -2, -4, -6.
Hints
- Maintain two running chains: one for odd-positioned nodes and one for even-positioned nodes.
- Save the head of the even chain before relinking so you can attach it after the odd chain at the end.