Chat app~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-234linked-lists · two-pointers
A chat app has a word game for mirror threads. A thread is a mirror when its sticker codes read the same from the first message to the last as from the last to the first.
The app keeps a thread as a chain of nodes, and a thread can hold up to 100,000 messages. The game checks a thread many times, so it must not copy the thread: a copy of a long thread costs memory on every check.
Write is_mirror_thread(head).
head is the first node of the thread, or null when the thread is empty. Each node's val is a sticker code.true when the codes read the same in both directions, and false otherwise. An empty thread is a mirror.The tests give head as the list of values from the head.
Input: head = [3, 8, 5, 8, 3]
Output: true| Step | What happens | The chain now |
|---|---|---|
| 1. Find the middle | slow and fast walk; slow stops on the 5 | 3 → 8 → 5 → 8 → 3 |
| 2. Reverse from the middle | the part 5 → 8 → 3 turns around | 3 → 8 → 5 and, from the last node, 3 → 8 → 5 |
| 3. Compare | 3 = 3, 8 = 8, and the 5 meets itself | every pair matches: true |
| 4. Turn it back | the second half is reversed again | 3 → 8 → 5 → 8 → 3 |
With five messages the middle belongs to both halves, so it is compared with itself and always matches.
Input: head = [2, 6, 6, 2]
Output: trueFour messages have two middles, the two 6s. Slow stops on the second of them, so the halves are 2, 6 and 6, 2, and they match once the second is turned around.
Input: head = [4, 7, 9, 4]
Output: falseThe ends match, but the inner pair 7 and 9 does not. A mismatch can sit anywhere, so compare every pair.
0 ≤ number of nodes ≤ 10^50 ≤ node.val ≤ 9999Reaching a node by its position is a walk from the head. A check that walks to both ends of every pair makes about n^2 / 2 hops: 5 × 10^9 at this size, which is too slow.
Copying the codes into an array is fast, but it costs O(n) extra memory for every check, and the scenario rules it out. So find the middle, reverse one half in place, and walk the two halves together. That is O(n) time and O(1) extra memory.
A note on the tests: they check the answer only. The judge does not measure extra memory, so an array copy also passes, and it cannot see whether you turned the half back. Both rules are part of the task all the same, and an interviewer will ask about each.