Java Progressive Coding Master Bank (25 Algorithmic Questions)
25 practical Java coding interview challenges complete with optimal solutions, algorithmic explanations, space/time complexity analysis, and interactive knowledge check quizzes.
Q1: How do you reverse a String in-place without built-in reverse functions?
Strings in Java are immutable, so to reverse a String in-place, convert it to a char[] array and use the Two-Pointer Technique. Initialize pointers at both ends of the array, swap characters, and move the pointers toward the center until they meet.
public class StringReversal {
public static String reverse(String input) {
if (input == null || input.length() <= 1) return input;
char[] chars = input.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}
}Swaps characters from outside inward until the pointers cross.
Strings are immutable in Java; convert to
char[]for swapping.Two-pointer technique yields $O(n)$ time and $O(n)$ space complexity.
What is the time complexity of reversing a string of length N using the two-pointer approach on a char array?
Q2: How do you check if a String is a Palindrome (ignoring non-alphanumeric characters)?
Use two pointers (left at index 0, right at index len - 1). Increment left and decrement right past non-alphanumeric characters (Character.isLetterOrDigit), and compare lowercased characters.
public class ValidPalindrome {
public static boolean isPalindrome(String s) {
if (s == null) return false;
int left = 0, right = s.length() - 1;
while (left < right) {
while (left < right && !Character.isLetterOrDigit(s.charAt(left))) left++;
while (left < right && !Character.isLetterOrDigit(s.charAt(right))) right--;
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
}Skips special characters on the fly to check palindrome properties efficiently.
Filter non-alphanumeric characters dynamically using
Character.isLetterOrDigit().Runs in $O(n)$ time with $O(1)$ auxiliary space.
Why is scanning inward with Character.isLetterOrDigit preferred over s.replaceAll("[^a-zA-Z0-9]", "")?
Q3: How do you verify if two Strings are Anagrams?
Two strings are anagrams if they contain the exact same character frequencies. Check if lengths are equal first. Count character occurrences using a fixed-size integer frequency array (int[26] for lowercase English letters) or a HashMap for general Unicode.
public class ValidAnagram {
public static boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] counts = new int[26];
for (int i = 0; i < s.length(); i++) {
counts[s.charAt(i) - 'a']++;
counts[t.charAt(i) - 'a']--;
}
for (int count : counts) {
if (count != 0) return false;
}
return true;
}
}Accumulates and decrements frequencies in a single pass over both strings.
Use
int[26]array as a fast frequency map for ASCII alphabets.Increment count for string 1, decrement for string 2; verify all entries equal 0.
What is the space complexity of checking anagrams of lower-case ASCII strings using a fixed int[26] array?
Q4: How do you solve the Two Sum problem in O(n) time?
Given an array of integers and a target sum, return the indices of two numbers that add up to target. Use a HashMap<Integer, Integer> storing (value -> index). Iterate through the array once, computing complement = target - nums[i]. If complement exists in map, return current index and stored complement index.
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}Maps element values to array indices to resolve complement lookups instantly.
HashMap provides $O(1)$ lookup time for target complements.
Achieves $O(n)$ time complexity in a single pass.
What is the time complexity of finding a Two Sum pair using a Hash Table?
Q5: How do you find the first non-repeating character in a String?
Perform two passes over the string. Pass 1: Build a character frequency map (int[256] or LinkedHashMap). Pass 2: Iterate through the string from left to right; return the index of the first character whose frequency count equals 1.
public class FirstUniqueChar {
public static int firstUniqChar(String s) {
int[] freq = new int[256];
for (int i = 0; i < s.length(); i++) {
freq[s.charAt(i)]++;
}
for (int i = 0; i < s.length(); i++) {
if (freq[s.charAt(i)] == 1) return i;
}
return -1;
}
}Finds character frequencies in the first loop and locates the first unique element index in the second.
Pass 1 counts character frequencies.
Pass 2 preserves input ordering to identify the first unique character index.
Why does a second iteration over the string s (rather than iterating over the frequency array) guarantee finding the FIRST non-repeating character?
Q6: How do you find the single missing number in an array containing numbers 0 to n?
Use Gauss's Sum Formula: expected sum $S = frac{n(n + 1)}{2}$. Calculate the actual sum of array elements and subtract it from $S$. Alternatively, use XOR: $x oplus x = 0$, XORing indices and values leaves the missing number.
public class MissingNumber {
public static int findMissing(int[] nums) {
int xor = nums.length;
for (int i = 0; i < nums.length; i++) {
xor ^= i ^ nums[i];
}
return xor;
}
}XORing all indices and array values cancels out duplicate pairs, leaving the missing number.
Mathematical approach: $ ext{Expected Sum} - ext{Actual Sum} = ext{Missing Number}$.
XOR approach avoids potential integer overflow errors.
What primary advantage does the Bitwise XOR method have over Gauss's sum formula when n is very large?
Q7: How do you move all zeroes to the end of an array in-place while maintaining relative order?
Maintain a lastNonZeroFoundAt pointer initialized to 0. Iterate through the array; whenever a non-zero element is encountered, swap it with the element at lastNonZeroFoundAt and increment the pointer.
public class MoveZeroes {
public static void moveZeroes(int[] nums) {
int insertPos = 0;
for (int num : nums) {
if (num != 0) {
nums[insertPos++] = num;
}
}
while (insertPos < nums.length) {
nums[insertPos++] = 0;
}
}
}Overwrites non-zero values forward, then pads remaining indices with zeroes.
Two-pointer partitioning scheme.
Executes in $O(n)$ time with $O(1)$ auxiliary memory.
What is the total number of array writes required in the worst-case for the two-pass insertPos approach?
Q8: How do you reverse a Singly LinkedList iteratively in O(n) time and O(1) space?
Maintain three pointers: prev (initialized to null), curr (initialized to head), and next. Traverse the list: store curr.next in next, reverse curr.next to point to prev, advance prev to curr, and advance curr to next. Return prev as the new head.
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public class ReverseLinkedList {
public static ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
}Rebinds pointer targets step-by-step until the list traversal completes.
Use
prev,curr, andnextpointers to reverse node pointers in place.$O(n)$ time complexity, $O(1)$ space complexity.
What does the prev pointer point to at the conclusion of the iterative reversal loop?
Q9: How do you detect a cycle in a LinkedList using Floyd's Cycle-Finding Algorithm?
Use Floyd's Tortoise and Hare Algorithm. Initialize two pointers: slow and fast at head. Move slow by 1 step and fast by 2 steps. If a cycle exists, fast and slow will eventually meet at the same node. If fast reaches null, no cycle exists.
public class LinkedListCycle {
public static boolean hasCycle(ListNode head) {
if (head == null) return false;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
}If the fast pointer laps the slow pointer, a cycle exists in the list.
Two pointers moving at different speeds ($1 imes$ vs $2 imes$).
Detects cycles in $O(n)$ time using $O(1)$ memory.
Why is Floyd's Cycle detection algorithm preferred over storing visited nodes in a HashSet?
Q10: How do you validate balanced brackets and parentheses using a Stack?
Traverse the string character by character. When encountering an opening bracket ((, {, [), push its corresponding matching closing bracket onto a Deque<Character> stack. When encountering a closing bracket, check if the stack is empty or if the popped element matches. Return stack.isEmpty() at the end.
import java.util.ArrayDeque;
import java.util.Deque;
public class ValidParentheses {
public static boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(') stack.push(')');
else if (c == '{') stack.push('}');
else if (c == '[') stack.push(']');
else if (stack.isEmpty() || stack.pop() != c) return false;
}
return stack.isEmpty();
}
}Pushing expected closing brackets makes matching simple.
Push expected closing characters to simplify validation logic.
Return
stack.isEmpty()to handle unclosed opening brackets.
What is the stack state when processing an invalid input string with unmatched opening brackets like "((("?
Q11: How do you find the contiguous subarray with the largest sum using Kadane's Algorithm?
Maintain two variables: maxEndingHere and maxSoFar. Iterate through the array. For each element, decide whether to add it to the existing subarray sum or start a new subarray at the current element: maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]). Update maxSoFar = Math.max(maxSoFar, maxEndingHere).
public class MaximumSubarray {
public static int maxSubArray(int[] nums) {
int maxSoFar = nums[0];
int maxEndingHere = nums[0];
for (int i = 1; i < nums.length; i++) {
maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
}Tracks maximum subarray sums ending at each index in a single pass.
Kadane's Algorithm executes Dynamic Programming in $O(n)$ time.
Decides whether to extend the current sum or reset at the current element.
What does Kadane's Algorithm return if all elements in the input array are negative numbers (e.g., [-3, -1, -5])?
Q12: How do you solve Container With Most Water using Two Pointers?
Given $n$ vertical lines, find two lines that form a container storing the most water. Initialize pointers at both ends (left = 0, right = len - 1). Calculate area: $text{width} times min(text{height}[left], text{height}[right])$. Move the pointer pointing to the shorter line inward, as moving the taller line can never yield a larger area.
public class ContainerWithMostWater {
public static int maxArea(int[] height) {
int maxWater = 0;
int left = 0, right = height.length - 1;
while (left < right) {
int h = Math.min(height[left], height[right]);
int w = right - left;
maxWater = Math.max(maxWater, h * w);
if (height[left] < height[right]) left++;
else right--;
}
return maxWater;
}
}Shrinks container width while attempting to discover larger height boundaries.
Two pointers start at array boundaries.
Move the pointer with the smaller height inward to seek a larger container area.
Why is moving the pointer pointing to the taller line guaranteed NOT to increase the container area?
Q13: How do you find the length of the Longest Substring Without Repeating Characters using Sliding Window?
Maintain a dynamic Sliding Window bounded by left and right pointers, along with a HashMap<Character, Integer> mapping characters to their most recent index. As right scans forward, if a duplicate character is found at index $ge left$, jump left = map.get(char) + 1. Calculate maxLength = Math.max(maxLength, right - left + 1).
import java.util.HashMap;
import java.util.Map;
public class LongestSubstring {
public static int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int maxLength = 0, left = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
if (map.containsKey(c)) {
left = Math.max(left, map.get(c) + 1);
}
map.put(c, right);
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
}Jumps the left window boundary past duplicate characters using hash index tracking.
Sliding Window with fast pointer jumping via index lookup maps.
Achieves $O(n)$ time complexity in a single pass.
Why is left updated using left = Math.max(left, map.get(c) + 1) rather than left = map.get(c) + 1 directly?
Q14: How do you Merge Overlapping Intervals in an array?
- Sort the intervals by their start times:
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])). - Iterate through intervals and maintain a merged list. If the current interval's start time $le$ the last merged interval's end time, merge them by updating
last.end = Math.max(last.end, current.end). Otherwise, append the current interval.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MergeIntervals {
public static int[][] merge(int[][] intervals) {
if (intervals.length <= 1) return intervals;
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> result = new ArrayList<>();
int[] current = intervals[0];
result.add(current);
for (int[] interval : intervals) {
if (interval[0] <= current[1]) {
current[1] = Math.max(current[1], interval[1]);
} else {
current = interval;
result.add(current);
}
}
return result.toArray(new int[result.size()][]);
}
}Sorts intervals by start time and merges overlapping boundary spans in linear order.
Sorting by start time guarantees overlapping intervals are adjacent.
Time Complexity: $O(n log n)$ due to initial sorting pass.
What is the time complexity bottleneck in the Merge Intervals algorithm?
Q15: How do you find the Kth Largest Element in an Array using a Min-Heap and QuickSelect?
- Min-Heap Approach: Maintain a
PriorityQueueof size $k$. Iterate elements; push onto heap. If size $> k$, pop the minimum. Final heap top contains the $k$-th largest element. Time: $O(n log k)$. - QuickSelect Approach: Based on Partition step from QuickSort. Average time: $O(n)$.
import java.util.PriorityQueue;
public class KthLargest {
public static int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int num : nums) {
minHeap.add(num);
if (minHeap.size() > k) {
minHeap.poll();
}
}
return minHeap.peek();
}
}Restricting heap capacity to $k$ elements leaves the $k$-th largest item at the top.
Min-Heap of size $k$ maintains the $k$ largest elements seen so far.
QuickSelect provides average $O(n)$ time complexity using partitioning.
What is the space complexity of finding the Kth largest element using a size-bounded Min-Heap?
Q16: How do you find the Lowest Common Ancestor (LCA) of two nodes in a Binary Tree?
Use a recursive post-order traversal. If root == null, root == p, or root == q, return root. Recursively search left and right subtrees. If both left and right recursive calls return non-null nodes, root is the LCA. If only one returns non-null, pass that node upward.
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public class LCA {
public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) return root;
return (left != null) ? left : right;
}
}Bubbles up matches from left and right subtrees to identify the common ancestor node.
Recursive post-order traversal checks left and right subtrees.
If both branches return target nodes, current root is the LCA.
What is the time complexity of finding the LCA in an unbalanced Binary Tree with N nodes?
Q17: How do you perform Level Order Traversal (BFS) on a Binary Tree?
Use Breadth-First Search (BFS) with a Queue<TreeNode>. Offer root to queue. While queue is not empty, measure levelSize = queue.size(). Loop levelSize times to process nodes on the current level, polling nodes and offering non-null child nodes.
import java.util.*;
public class LevelOrder {
public static List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> currentLevel = new ArrayList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
currentLevel.add(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
result.add(currentLevel);
}
return result;
}
}Uses queue snapshot sizes to partition nodes into level-by-level list arrays.
BFS traversal utilizes a Queue data structure.
Process levels in batches using snapshot level sizes (
queue.size()).
Why is recording levelSize = queue.size() BEFORE the level for-loop critical?
Q18: How do you Serialize and Deserialize a Binary Tree?
- Serialization: Convert tree to string using Pre-Order DFS traversal, appending
"#"or"null"for null pointers, separated by commas. - Deserialization: Split string by comma into a
Queue<String>. Reconstruct tree recursively by polling values, creating nodes, and assigning left/right child subtrees.
import java.util.*;
public class Codec {
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
buildString(root, sb);
return sb.toString();
}
private void buildString(TreeNode node, StringBuilder sb) {
if (node == null) { sb.append("#,"); return; }
sb.append(node.val).append(",");
buildString(node.left, sb);
buildString(node.right, sb);
}
public TreeNode deserialize(String data) {
Queue<String> nodes = new LinkedList<>(Arrays.asList(data.split(",")));
return buildTree(nodes);
}
private TreeNode buildTree(Queue<String> nodes) {
String val = nodes.poll();
if (val.equals("#")) return null;
TreeNode node = new TreeNode(Integer.parseInt(val));
node.left = buildTree(nodes);
node.right = buildTree(nodes);
return node;
}
}Serializes nodes with null boundary markers and reconstructs tree nodes in pre-order.
Pre-order DFS traversal with null markers enables unambiguous tree reconstruction.
Queue-based deserialization matches pre-order node creation.
Why are explicit null markers (e.g. "#") necessary when serializing a binary tree using pre-order traversal?
Q19: How do you solve Number of Islands using Graph Search (DFS / BFS)?
Iterate through the 2D grid matrix. When encountering '1' (land), increment island count and trigger DFS/BFS to sink connected land cells by mutating grid cells to '0' (or marking them visited). Repeat for all unvisited land cells.
public class NumberOfIslands {
public static int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) return 0;
int count = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == '1') {
count++;
dfs(grid, r, c);
}
}
}
return count;
}
private static void dfs(char[][] grid, int r, int c) {
if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] == '0') {
return;
}
grid[r][c] = '0'; // Sink land
dfs(grid, r + 1, c);
dfs(grid, r - 1, c);
dfs(grid, r, c + 1);
dfs(grid, r, c - 1);
}
}Traverses and sinks adjacent land cells recursively when a new island is detected.
2D Grid Graph Traversal using DFS or BFS.
In-place land sinking (
'1'$ o$'0') eliminates $O(m imes n)$ auxiliary visited array memory.
What is the time complexity of the Number of Islands graph traversal on an M x N grid?
Q20: How do you solve Course Schedule I using Topological Sort (Kahn's Algorithm)?
Model course dependencies as a Directed Graph. Detect if a Cycle exists using Kahn's Algorithm (BFS Topological Sort):
- Build adjacency list and compute
inDegree[]array for each node. - Add all nodes with
inDegree == 0to a Queue. - While queue is non-empty, poll node, increment
processedCount, and decrementinDegreeof neighbor nodes. If neighborinDegreehits 0, offer to Queue. - Return
processedCount == numCourses.
import java.util.*;
public class CourseSchedule {
public static boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < numCourses; i++) adj.add(new ArrayList<>());
int[] inDegree = new int[numCourses];
for (int[] p : prerequisites) {
adj.get(p[1]).add(p[0]);
inDegree[p[0]]++;
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < numCourses; i++) {
if (inDegree[i] == 0) queue.offer(i);
}
int processed = 0;
while (!queue.isEmpty()) {
int curr = queue.poll();
processed++;
for (int neighbor : adj.get(curr)) {
if (--inDegree[neighbor] == 0) queue.offer(neighbor);
}
}
return processed == numCourses;
}
}Validates graph acyclicity by verifying that all courses can be processed in topological order.
Topological Sort detects cycles in Directed Graphs.
Kahn's algorithm processes nodes with 0 in-degree using BFS.
If a directed graph contains a cycle, what will processedCount equal at the end of Kahn's Algorithm?
Q21: How do you solve the Coin Change problem using Bottom-Up Dynamic Programming?
Find the fewest coins needed to make up amount. Define dp[i] as the minimum coins needed for amount i. Initialize dp array of size amount + 1 filled with amount + 1 (infinity placeholder), with dp[0] = 0.
Outer loop: i from 1 to amount. Inner loop: each coin in coins. If i - coin >= 0, update dp[i] = Math.min(dp[i], 1 + dp[i - coin]). Return dp[amount] > amount ? -1 : dp[amount].
import java.util.Arrays;
public class CoinChange {
public static int coinChange(int[] coins, int amount) {
int max = amount + 1;
int[] dp = new int[amount + 1];
Arrays.fill(dp, max);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int coin : coins) {
if (i - coin >= 0) {
dp[i] = Math.min(dp[i], 1 + dp[i - coin]);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
}Computes the minimum coin count for target amounts up to amount.
Bottom-Up 1D Dynamic Programming.
State Relation: $dp[i] = min(dp[i], 1 + dp[i - coin])$.
What is the time complexity of the Bottom-Up Coin Change Dynamic Programming solution?
Q22: How do you solve Longest Increasing Subsequence (LIS) in O(n log n) time using Patience Sorting?
Maintain a dynamic list tails storing the smallest tail element for all increasing subsequences of various lengths. Iterate through nums. Use Arrays.binarySearch() to locate insertion index of x in tails:
- If
xis larger than all elements, append totails. - Otherwise, overwrite the first element in
tails$ge x$. Length oftailsis the LIS length.
import java.util.Arrays;
public class LIS {
public static int lengthOfLIS(int[] nums) {
int[] tails = new int[nums.length];
int size = 0;
for (int x : nums) {
int i = 0, j = size;
while (i < j) {
int mid = (i + j) / 2;
if (tails[mid] < x) i = mid + 1;
else j = mid;
}
tails[i] = x;
if (i == size) size++;
}
return size;
}
}Uses binary search to update tail elements in $O(n log n)$ time.
Patience Sorting with Binary Search provides $O(n log n)$ performance.
Maintains smallest tail values for increasing subsequences.
What does the size variable represent at the end of the Patience Sorting algorithm?
Q23: How do you design an LRU Cache with O(1) get and put operations?
Combine a HashMap<Integer, Node> with a Doubly Linked List (head and tail sentinel nodes):
HashMap: Provides $O(1)$ key-to-node lookups.- Doubly Linked List: Maintains recency ordering. On access/update, move node to
head($O(1)$). When capacity is exceeded, evict node beforetail($O(1)$).
import java.util.HashMap;
import java.util.Map;
public class LRUCache {
class Node {
int key, val;
Node prev, next;
Node(int k, int v) { key = k; val = v; }
}
private final int capacity;
private final Map<Integer, Node> map = new HashMap<>();
private final Node head = new Node(0, 0), tail = new Node(0, 0);
public LRUCache(int capacity) {
this.capacity = capacity;
head.next = tail; tail.prev = head;
}
public int get(int key) {
if (!map.containsKey(key)) return -1;
Node node = map.get(key);
remove(node); addFirst(node);
return node.val;
}
public void put(int key, int value) {
if (map.containsKey(key)) remove(map.get(key));
if (map.size() == capacity) {
map.remove(tail.prev.key);
remove(tail.prev);
}
Node node = new Node(key, value);
addFirst(node); map.put(key, node);
}
private void remove(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void addFirst(Node node) {
node.next = head.next;
node.prev = head;
head.next.prev = node;
head.next = node;
}
}Combines HashMap index lookups with Doubly Linked List node movements for $O(1)$ access and eviction.
HashMap + Doubly Linked List achieves $O(1)$ operations.
Sentinel
headandtailnodes simplify node addition/removal logic.
Why is a Doubly Linked List necessary instead of a Singly Linked List for O(1) LRU eviction?
Q24: How do you find the Median from a Data Stream using Two Heaps?
Maintain two heaps:
maxHeap(Max-Heap): Stores the smaller half of numbers.minHeap(Min-Heap): Stores the larger half of numbers.
addNum(num): Push tomaxHeap. MovemaxHeap.poll()tominHeap. IfminHeap.size() > maxHeap.size(), moveminHeap.poll()back tomaxHeap.findMedian(): If sizes equal, average of tops; otherwisemaxHeap.peek().
import java.util.Collections;
import java.util.PriorityQueue;
public class MedianFinder {
private final PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
private final PriorityQueue<Integer> minHeap = new PriorityQueue<>();
public void addNum(int num) {
maxHeap.offer(num);
minHeap.offer(maxHeap.poll());
if (minHeap.size() > maxHeap.size()) {
maxHeap.offer(minHeap.poll());
}
}
public double findMedian() {
if (maxHeap.size() > minHeap.size()) return maxHeap.peek();
return (maxHeap.peek() + minHeap.peek()) / 2.0;
}
}Balances two heap structures to retrieve stream medians in $O(1)$ time.
Max-Heap (small half) + Min-Heap (large half).
addNum: $O(log n)$ time;findMedian: $O(1)$ time.
What is the time complexity of the findMedian() method in the Two-Heap approach?
Q25: How do you solve Word Ladder (Shortest Transformation Sequence) using BFS?
Find the shortest transformation path from beginWord to endWord changing one letter at a time where intermediate words exist in wordList. Model as an unweighted graph where edges connect words differing by 1 character. Execute BFS starting at beginWord to guarantee finding the shortest path length.
import java.util.*;
public class WordLadder {
public static int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> set = new HashSet<>(wordList);
if (!set.contains(endWord)) return 0;
Queue<String> queue = new LinkedList<>();
queue.offer(beginWord);
int level = 1;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
char[] curr = queue.poll().toCharArray();
for (int j = 0; j < curr.length; j++) {
char original = curr[j];
for (char c = 'a'; c <= 'z'; c++) {
if (curr[j] == c) continue;
curr[j] = c;
String next = new String(curr);
if (next.equals(endWord)) return level + 1;
if (set.contains(next)) {
queue.offer(next);
set.remove(next); // Mark visited
}
}
curr[j] = original;
}
}
level++;
}
return 0;
}
}Generates character mutations and traverses transformation steps using BFS level by level.
BFS finds the shortest path in unweighted graphs.
Generate one-letter mutations dynamically to find adjacent valid dictionary words.
Why is Breadth-First Search (BFS) preferred over Depth-First Search (DFS) for Word Ladder?