Practice
Solution
Step 1: Trace slow and fast pointers
Initial: slow=1, fast=1; Iteration 1: slow=2, fast=3; Iteration 2: fast.next is null, loop ends.Step 2: Return slow's value
Slow points to node with value 3 at loop end.Final Answer:
Option B -> Option BQuick Check:
For even length, returns second middle node (3) [OK]
- Returning first middle node for even length
- Off-by-one errors in loop condition
- Confusing slow and fast pointer positions
Solution
Step 1: Identify the problem constraints
The problem requires checking palindrome in O(n) time and O(1) space.Step 2: Evaluate approaches
Converting to array uses O(n) space, recursion uses O(n) stack space, and hash set is not suitable for palindrome check. Using fast and slow pointers to reverse second half in-place meets both time and space requirements.Final Answer:
Option A -> Option AQuick Check:
Optimal approach uses fast-slow pointers and in-place reversal [OK]
- Assuming array conversion is optimal due to simplicity
- Believing recursion uses constant space
- Using hash sets for palindrome detection
Solution
Step 1: Count total nodes and compute sizes
List length = 3, k = 5, so part_size = 0, remainder = 3.Step 2: Assign nodes to parts
First 3 parts get 1 node each (due to remainder), last 2 parts get null (empty).Final Answer:
Option B -> Option BQuick Check:
parts[0]=1, parts[1]=2, parts[2]=3, parts[3]=null, parts[4]=null, so parts[2] points to node with value 3 [OK]
- Assuming all parts have nodes
- Off-by-one in indexing parts
- Confusing node values with indices
Solution
Step 1: Identify cost per iteration
Each iteration computes sum of squares of digits. Number of digits in n is proportional to log n, so each iteration is O(log n).Step 2: Multiply by number of iterations k
The process repeats k times until reaching 1 or cycle. Total time is O(k * log n).Final Answer:
Option B -> Option BQuick Check:
Sum of digits per iteration is log n, repeated k times -> O(k * log n) [OK]
- Confusing n with number of digits, assuming O(n) per iteration
Solution
Step 1: Identify data structures used
The stack stores every node in the list, so it holds n nodes.Step 2: Determine space complexity
Storing all n nodes means O(n) auxiliary space is required.Step 3: Re-examine options
O(n) because all nodes are stored in the stack states O(n) space which is correct for stack-based approach. O(1) because only a few pointers are used states O(1) which is incorrect for stack-based approach.Final Answer:
Option A -> Option AQuick Check:
Stack size grows linearly with list length [OK]
- Assuming constant space due to pointers
- Confusing recursion stack with iterative stack
- Thinking divide and conquer applies here
