Data Structures & AlgorithmsHardTCS Digital · Infosys SP
You must check whether a singly linked list of n nodes is a palindrome using O(1) extra space. Which approach works in O(n) time?
- A. Copy the values into an array and use two pointers
- B. Find the middle with slow/fast pointers, reverse the second half, compare the halves, then (optionally) reverse it back
- C. Recursively compare first and last nodes, removing the last each time
- D. Push all nodes onto a stack and compare
Correct answer: B. Find the middle with slow/fast pointers, reverse the second half, compare the halves, then (optionally) reverse it back
The stack and the array use O(n) space; repeatedly finding the last node is O(n²). Reversing the second half in place uses O(1) extra space and linear time.
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
- The intervals [4, 8], [13, 15], [5, 8], [8, 11], [12, 16], [8, 11] are sorted by start and merged (intervals that touch, like [2, 4] and…
- Find the leaders (elements strictly greater than everything to their right) by scanning from the right. What is printed? python a = [17…
- Count distinct values in every window of size k with a frequency map. What is printed? python from collections import Counter a, k = [2…
- Quickselect returns the k-th smallest element of an unsorted array in expected O(n) time. For [14, 4, 8, 46, 16, 34, 31, 40] and k = 3…
- How many contiguous subarrays of [6, 4, 2, 5, 6, 2, 3, 3] have a product strictly less than 30? (Positive values: a two-pointer window…
- Rotate a linked list to the RIGHT by k places (k may exceed the length). What is printed? python def rotate(h, k): n, t = 1, h while t.nx…