0% found this document useful (0 votes)
2 views23 pages

Java Code Question

The document outlines essential topics and skills for Java coding interviews, focusing on practical coding abilities in areas such as string manipulation, data structures, algorithms, and object-oriented programming. It includes a list of 100 Java coding problems categorized by difficulty and tags, along with hints and key concepts for each problem. Resources for further study are also provided, including Oracle’s Java Tutorials and popular coding platforms.

Uploaded by

gauravmishra5210
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views23 pages

Java Code Question

The document outlines essential topics and skills for Java coding interviews, focusing on practical coding abilities in areas such as string manipulation, data structures, algorithms, and object-oriented programming. It includes a list of 100 Java coding problems categorized by difficulty and tags, along with hints and key concepts for each problem. Resources for further study are also provided, including Oracle’s Java Tutorials and popular coding platforms.

Uploaded by

gauravmishra5210
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Executive Summary

Java interviews emphasize practical coding skills across core topics. Common areas include string and
array manipulation, object-oriented design, recursion and data structures (e.g. linked lists, stacks,
maps)【6†L222-L230】. You should be comfortable with algorithms like sorting/searching and techniques
like two-pointers or sliding windows. Expect questions on OOP principles (inheritance, interfaces,
polymorphism) and newer Java features (lambdas, streams)【6†L228-L236】. Concurrent programming is
often probed through deadlock or thread-safety scenarios【6†L232-L234】. The compiled list of 100 Java
coding problems below covers these areas, each labeled with difficulty, tags, and estimated solve time.
Concise hints and key concepts follow each problem. For deeper study, see Oracle’s Java Tutorials【26†L73-
L80】, the OpenJDK project resources, “Effective Java”【30†L61-L69】, and coding platforms like LeetCode
【32†L1-L2】 and GeeksforGeeks【34†L29-L32】.

Est.
ID Problem Statement Difficulty Tags
Time

1 Reverse a string. Easy Strings 5 min

2 Check if a string is a palindrome. Easy Strings 5 min

Check if two strings are anagrams of each


3 Medium Strings, Hashing 10 min
other.

4 Find duplicate characters in a string. Medium Strings, Hashing 10 min

5 Remove vowels from a string. Easy Strings, Regex 5 min

6 Count distinct characters in a string. Medium Strings, Hashing 10 min

Find longest common prefix among an array


7 Medium Strings, Sorting 10 min
of strings.

8 Replace spaces in a string with “%20” (URLify). Easy Strings 5 min

Check if a string contains only digits using


9 Easy Strings, Regex 5 min
regex.

10 Validate an email address using regex. Medium Strings, Regex 10 min

11 Reverse an array of integers. Easy Arrays 5 min

12 Rotate an array by k positions. Medium Arrays, Two Pointers 10 min

13 Move all zeros in an array to the end. Easy Arrays, Two Pointers 5 min

14 Find the second largest element in an array. Easy Arrays 5 min

1
Est.
ID Problem Statement Difficulty Tags
Time

Max profit from stock buy/sell (one


15 Medium Arrays, Greedy 10 min
transaction).

Max profit from stock buy/sell (unlimited


16 Medium Arrays, Greedy 10 min
transactions).

17 Remove duplicates from a sorted array. Easy Arrays, Two Pointers 5 min

Two-sum: find indices of two numbers adding


18 Medium Arrays, HashMap 10 min
to target.

Maximum subarray sum (Kadane’s


19 Medium Arrays, Greedy 10 min
algorithm).

20 Print a 2D matrix in spiral order. Medium Arrays 10 min

21 Transpose a matrix. Easy Arrays 5 min

22 Search an element in a sorted rotated array. Hard Arrays, Binary Search 15 min

Find a missing number in an array (numbers


23 Medium Arrays, Math 10 min
1..N).

Arrays, HashMap, Two


24 Find a subarray with a given sum. Medium 10 min
Pointers

Sort an array using built-in methods (e.g.


25 Easy Arrays, Sorting 5 min
[Link] ).

26 Merge two sorted arrays. Easy Arrays, Two Pointers 5 min

27 Find the intersection of two arrays. Medium Arrays, HashSet 10 min

28 Shuffle (randomize) an array’s order. Medium Arrays, Math 10 min

29 Compute the sum of all elements in an array. Easy Arrays 5 min

30 Check if all elements in a list are odd. Easy Collections, Streams 5 min

31 Concatenate two lists into a third list. Easy Collections 5 min

Find duplicate in an array of N+1 integers


32 Hard Arrays, HashSet 15 min
(pigeonhole).

Rearrange array elements in alternating pos/


33 Medium Arrays 10 min
neg sequence.

34 (Removed / see Ex.) — — —

35 Check if a year is a leap year. Easy Math 5 min

36 Reverse a linked list. Medium LinkedList 10 min

2
Est.
ID Problem Statement Difficulty Tags
Time

LinkedList, Two
37 Detect a cycle in a linked list. Hard 15 min
Pointers, HashSet

38 Merge two sorted linked lists. Easy LinkedList 5 min

Remove the n-th node from end of a linked


39 Medium LinkedList, Two Pointers 10 min
list.

40 Check if a linked list is a palindrome. Medium LinkedList 10 min

41 Implement a stack using two queues. Medium Data Structures 10 min

42 Implement a queue using two stacks. Medium Data Structures 10 min

Evaluate a postfix (Reverse Polish)


43 Medium Stack 10 min
expression.

44 Check if parentheses in a string are balanced. Easy Stack 5 min

45 Next greater element for each array element. Medium Stack, Arrays 10 min

46 Inorder traversal of a binary tree. Easy Tree 5 min

47 Check if a binary tree is a BST. Medium Tree 10 min

48 Lowest Common Ancestor in a BST. Medium Tree 10 min

49 Check if two trees are mirrors of each other. Medium Tree 10 min

50 Level-order traversal of a tree. Easy Tree 5 min

51 Breadth-First Search (BFS) of a graph. Medium Graph 10 min

52 Detect a cycle in a directed graph. Hard Graph 15 min

Topological sort of a directed acyclic graph


53 Hard Graph 15 min
(DAG).

54 Depth-First Search (DFS) of a graph. Medium Graph 10 min

55 Binary search in a sorted array. Easy Arrays, Binary Search 5 min

56 Merge sort implementation. Hard Sorting 15 min

57 Quick sort implementation. Hard Sorting 15 min

Find k-th smallest element in an unsorted


58 Medium Heap, Arrays 10 min
array.

59 Count inversions in an array. Hard Divide and Conquer 15 min

60 Check if a number is prime. Easy Math 5 min

61 Compute Fibonacci (recursive). Easy Recursion 5 min

3
Est.
ID Problem Statement Difficulty Tags
Time

62 Compute factorial of an integer. Easy Recursion, Math 5 min

63 Compute n-th Fibonacci (DP). Medium Dynamic Programming 10 min

Compute GCD of two numbers (Euclid’s


64 Easy Math 5 min
algorithm).

65 Compute LCM of two numbers. Easy Math 5 min

66 Check if a number is a power of two. Easy Bit Manipulation 5 min

67 Longest Increasing Subsequence in an array. Hard Dynamic Programming 15 min

0/1 Knapsack problem (max value under


68 Hard Dynamic Programming 15 min
weight limit).

69 Coin Change (minimum coins) problem. Medium Dynamic Programming 10 min

Longest Common Subsequence of two


70 Hard Dynamic Programming 15 min
strings.

71 Word Break (DP with dictionary). Hard Dynamic Programming 15 min

Example of class inheritance and method


72 Easy OOP 5 min
overriding.

Interface with default and static methods


73 Easy OOP, Java 8 5 min
example.

Diamond problem scenario with interfaces


74 Medium OOP, Inheritance 10 min
(default methods).

Explain overloading vs. overriding with


75 Easy OOP 5 min
examples.

76 Singleton design pattern implementation. Medium Design Patterns 10 min

77 Factory design pattern example. Medium Design Patterns 10 min

78 Observer design pattern example. Hard Design Patterns 15 min

79 Use a lambda expression to sort a list. Easy Java 8, Streams 5 min

80 Filter and map operations on a Java Stream. Medium Java 8, Streams 10 min

81 Sort a HashMap by its values. Medium Collections, Streams 10 min

Example of a generic class and a generic


82 Easy Generics 5 min
method.

Use Optional to safely handle potentially


83 Easy Java 8 5 min
null values.

4
Est.
ID Problem Statement Difficulty Tags
Time

Format the current date using Java’s Date-


84 Easy Java 8, Date-Time 5 min
Time API.

85 Create a deadlock situation with two threads. Hard Concurrency 15 min

Solve Producer-Consumer problem using


86 Hard Concurrency 15 min
threads.

Thread-safety: example using a synchronized


87 Medium Concurrency 10 min
block.

Differences between [Link]() and


88 Medium Concurrency 10 min
[Link]() .

Use ConcurrentHashMap in multithreaded Concurrency,


89 Medium 10 min
code. Collections

90 Read a text file line by line. Easy I/O 5 min

91 Write text to a file in Java. Easy I/O 5 min

92 Serialize and deserialize a Java object. Medium I/O, Serialization 10 min

93 Try-with-resources usage example. Easy Java 7+, I/O 5 min

94 Regex: Validate if a string is a valid email. Medium Regex 10 min

95 Regex: Check if a string contains only letters. Easy Regex 5 min

96 Implement a simple stack from scratch. Medium Data Structures 10 min

97 Implement a simple queue from scratch. Medium Data Structures 10 min

Command-line arguments: write a program


98 Easy Language 5 min
that prints them.

Check if an integer is a palindrome (no extra


99 Easy Math, Number 5 min
space).

Convert an integer to a binary string


100 Medium Bit Manipulation 10 min
manually.

Hints and Key Concepts


• Q1. Reverse a string: Hint: Use a StringBuilder (or loop from end to start) to build the reversed
string. Concept: String manipulation using StringBuilder since String is immutable【27†L1-
L3】.
• Q2. Palindrome string: Hint: Compare characters from both ends or reverse the string and check
equality. Concept: Two-pointer technique and string comparison.

5
• Q3. Anagram check: Hint: Sort both strings or count character frequencies (e.g. with a HashMap or
int[26]). Concept: Hashing or sorting to test character multiset equality.
• Q4. Duplicate characters: Hint: Use a HashMap or boolean array to count occurrences while
iterating. Concept: Counting frequency to find repeats.
• Q5. Remove vowels: Hint: Iterate through the string, appending only non-vowel chars. You can use
regex ( replaceAll("[aeiouAEIOU]", "") ). Concept: String traversal and regex or filtering.
• Q6. Distinct characters: Hint: Use a Set or boolean array to track seen characters, count unique
ones. Concept: Data structures (Set) for uniqueness.
• Q7. Longest common prefix: Hint: Compare characters of first string to others index by index or
sort array and compare first/last. Concept: Iterative comparison or sorting of strings.
• Q8. Replace spaces (URLify): Hint: Build a new string: replace each space with "%20". Concept: String
manipulation, careful of extra spaces or in-place (not available in Java String ).
• Q9. Only digits: Hint: Use regex like matches("\\d+") or try parsing with [Link] .
Concept: Regular expressions for pattern checking.
• Q10. Email regex: Hint: Use a pattern like ^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$ . Concept:
Regex validation.
• Q11. Reverse array: Hint: Swap elements in-place (swap arr[i] with arr[n-1-i] ). Concept:
Two-pointer technique on arrays.
• Q12. Rotate array: Hint: You can shift elements or use reverse-swap trick: reverse entire array, then
reverse subparts. Concept: Array indexing and modular arithmetic.
• Q13. Move zeros: Hint: Two-pointer (fast-slow) sweep: copy non-zeros forward, then fill rest with 0.
Concept: In-place array rearrangement.
• Q14. 2nd largest element: Hint: Track largest and second-largest in one pass. Concept: Simple linear
scan, keep two maxima.
• Q15. Stock profit (1 txn): Hint: Single pass, track min price so far and max profit. Concept: Greedy
(sliding window for max difference).
• Q16. Stock profit (mult. txns): Hint: Sum all positive differences (buy low, sell high repeatedly).
Concept: Greedy (sum of upward segments).
• Q17. Remove duplicates sorted: Hint: Two-pointer in-place: one pointer expands unique array end,
one scans. Concept: Array overwrite to remove duplicates.
• Q18. Two-sum: Hint: Use a HashMap storing needed complement -> index while scanning. Concept:
Hash table for lookup in linear time.
• Q19. Max subarray (Kadane): Hint: Track current sum; reset to 0 if negative. Concept: Dynamic
programming / greedy for subarray sum.
• Q20. Spiral matrix print: Hint: Walk boundaries (top, right, bottom, left), shrinking them each layer.
Concept: Simulation of matrix boundary traversal.
• Q21. Transpose matrix: Hint: Swap matrix[i][j] with matrix[j][i] for all i<j. Concept:
Matrix index manipulation.
• Q22. Search rotated array: Hint: Modified binary search: check which half is sorted and decide
which side target lies. Concept: Binary search in a rotated context (divide and conquer).

flowchart TB
A[Start] --> B{arr[mid] == target?}
B -- Yes --> C[Return mid index]
B -- No --> D{arr[left] <= arr[mid]?}
D -- Yes --> E{target >= arr[left] && target < arr[mid]}
D -- No --> F{target > arr[mid] && target <= arr[right]}

6
E -- Yes --> G[Search left half]
E -- No --> H[Search right half]
F -- Yes --> H
F -- No --> G
G --> I[Repeat binary search on left]
H --> J[Repeat binary search on right]
I --> C
J --> C

• Q23. Missing number: Hint: Compute expected sum 1..N and subtract actual sum, or use XOR of all.
Concept: Mathematical summation or bitwise XOR trick.
• Q24. Subarray with given sum: Hint: Two-pointer (for positives) or HashMap for prefix sums if
negatives allowed. Concept: Sliding window or prefix-sum + hash.
• Q25. Sort array: Hint: Just call [Link](arr) . Concept: Built-in sort (dual-pivot quicksort)
【6†L229-L231】.
• Q26. Merge sorted arrays: Hint: Use two indices to merge into a new array. Concept: Two-pointer
merge algorithm.
• Q27. Array intersection: Hint: Put one array into a HashSet , iterate the other to check. Concept:
Set membership testing.
• Q28. Shuffle array: Hint: Use the Fisher–Yates algorithm: swap each element with a random later
one. Concept: Randomization of arrays.
• Q29. Sum all elements: Hint: Loop and accumulate total. Concept: Simple reduction (can use streams
[Link](arr).sum() ).
• Q30. All odd check: Hint: Iterate or use stream().allMatch(x -> x%2!=0) . Concept: Stream
filters or predicate testing on collections.
• Q31. Concatenate lists: Hint: Add all elements of list B to list A (or vice versa). Concept: Collections
merging (e.g. addAll ).
• Q32. Duplicate in N+1: Hint: Use a HashSet or Floyd’s cycle detection on “value as next index”.
Concept: Pigeonhole principle, cycle detection.
• Q33. Alternate pos/neg: Hint: Partition positives/negatives then interleave; or use two pointers
swapping. Concept: Array reordering by sign.
• Q35. Leap year check: Hint: Year is leap if divisible by 4, but not by 100 unless also by 400. Concept:
Control flow and modulus.
• Q36. Reverse linked list: Hint: Iteratively update next pointers: keep track of previous node.
Concept: Pointer manipulation in linked lists.
• Q37. Detect cycle (Floyd): Hint: Use slow and fast pointers; if they meet, a cycle exists. Concept: Two-
pointer cycle detection.
• Q38. Merge sorted lists: Hint: Iterate both lists, appending the smaller current node to result.
Concept: Linked list merge like merge-sort.
• Q39. Remove nth from end: Hint: Use two-pointer: advance first by n, then move both until first hits
end. Concept: Gap technique on lists.
• Q40. Palindrome list: Hint: Reverse second half and compare to first half. Concept: Linked list
manipulation + palindrome check.
• Q41. Stack via queues: Hint: On push, enqueue to empty queue then pour old queue into it. Pop =
dequeue. Concept: Data structure emulation using queues.
• Q42. Queue via stacks: Hint: Use two stacks: push to stack1 ; on dequeue, if stack2 empty,
transfer all from stack1 then pop. Concept: Data structure emulation using stacks.

7
• Q43. Postfix evaluation: Hint: Use a stack: on operand push, on operator pop two and apply.
Concept: Stack-based expression evaluation.
• Q44. Balanced parentheses: Hint: Push opening brackets, pop on matching closing; ensure stack
empty at end. Concept: Stack for matching delimiters.
• Q45. Next greater element: Hint: Use a stack to maintain candidates: iterate array, pop from stack
when current is greater. Concept: Monotonic stack technique.
• Q46. Inorder tree traversal: Hint: Recursion on left, node, then right. Concept: DFS traversal
(inorder).
• Q47. Check BST: Hint: Recursively ensure each node’s value lies in valid min/max bounds. Concept:
Recursive tree validation.
• Q48. LCA in BST: Hint: Walk down from root: if both nodes < root go left, if both > root go right, else
root is LCA. Concept: Use BST ordering.
• Q49. Mirror trees: Hint: Recursively check left1 vs right2 and vice versa. Concept: Tree
symmetry check.
• Q50. Level-order traversal: Hint: Use a queue: enqueue root, then loop: dequeue node, enqueue its
children. Concept: BFS on trees.
• Q51. BFS graph: Hint: Use a queue; mark visited to avoid repeats. Concept: Graph breadth-first
search.
• Q52. Cycle in directed graph: Hint: Use DFS with coloring (recursion stack) or Kahn’s algorithm for
cycle. Concept: Graph cycle detection via DFS.
• Q53. Topological sort: Hint: Use DFS post-order or Kahn’s algorithm with in-degrees. Concept:
Ordering in DAGs using DFS or BFS.
• Q54. DFS graph: Hint: Recursion or explicit stack from a start node, mark visited. Concept: Graph
depth-first search.
• Q55. Binary search: Hint: Repeatedly compare target to mid of current range, halve range. Concept:
Divide-and-conquer search; see flowchart above.
• Q56. Merge sort: Hint: Recursively split array, sort halves, then merge. Concept: Divide-and-conquer
sort.
• Q57. Quick sort: Hint: Choose a pivot, partition array into < and > pivot, recurse on partitions.
Concept: Divide-and-conquer sort.
• Q58. k-th smallest (heap): Hint: Use a min-heap (or max-heap of size k). Concept: Priority queue
selection.
• Q59. Count inversions: Hint: Modify merge sort to count cross-inversions. Concept: Divide-and-
conquer counting.
• Q60. Prime check: Hint: Test divisibility up to √n. Concept: Loop / optimized trial division.
• Q61. Fibonacci (recursive): Hint: return fib(n-1)+fib(n-2) with base cases. Concept: Simple
recursion (inefficient).
• Q62. Factorial: Hint: Loop multiplication or recursive. Concept: Recursion/iteration of mathematical
formula.
• Q63. Fibonacci (DP): Hint: Use an array or variables to iteratively compute up to n. Concept: Dynamic
programming / iterative optimization.
• Q64. GCD (Euclid): Hint: Use recursive gcd(a,b) = gcd(b, a%b) . Concept: Euclidean algorithm.
• Q65. LCM: Hint: lcm(a,b) = |a*b| / gcd(a,b) . Concept: Math formula using GCD.
• Q66. Power of two: Hint: Check n > 0 && (n & (n-1)) == 0 . Concept: Bit manipulation trick.
• Q67. LIS: Hint: DP O(n^2) or patience sorting O(n log n). Concept: Longest increasing subsequence
problem.
• Q68. 0/1 Knapsack: Hint: DP table dp[i][w] for choices. Concept: Classic DP optimization.

8
• Q69. Coin Change: Hint: DP using min-coin table or greedy if coins fit. Concept: Unbounded knapsack
variant.
• Q70. LCS: Hint: DP table comparing prefixes of two strings. Concept: String DP.
• Q71. Word Break: Hint: DP or BFS on positions with a dictionary check. Concept: DP or backtracking
with memo.
• Q72. Inheritance example: Hint: Write a subclass extending a superclass and override a method.
Concept: Polymorphism (method overriding) in Java.
• Q73. Interface default methods: Hint: Define an interface with a default method; implement it in a
class. Concept: Java 8 interface enhancements.
• Q74. Diamond problem with interfaces: Hint: Show two interfaces with same default method and a
class implements both (resolving conflict). Concept: Multiple inheritance via interfaces.

classDiagram
interface InterfaceA {
+defaultMethod()
}
interface InterfaceB {
+defaultMethod()
}
class Implementer implements InterfaceA, InterfaceB {
+defaultMethod()
}

• Q75. Overloading vs Overriding: Hint: Give examples: same name diff params (overload) vs same
signature in subclass (override). Concept: Compile-time vs runtime polymorphism.
• Q76. Singleton pattern: Hint: Use a private constructor and a public static instance method (with or
without synchronization). Concept: Design pattern ensuring one instance.
• Q77. Factory pattern: Hint: Define a Factory class that creates objects based on input. Concept:
Encapsulating object creation.
• Q78. Observer pattern: Hint: Show Subject and Observer interfaces with add/remove/notify
methods. Concept: Publish-subscribe pattern.
• Q79. Lambda sort: Hint: E.g. [Link]((a,b) -> [Link]() - [Link]()); . Concept:
Java 8 lambdas for Comparator .
• Q80. Stream filter/map: Hint: E.g. [Link]().filter(x->x>0).map(x-
>x*x).collect(...) . Concept: Functional operations on streams.
• Q81. Sort HashMap by values: Hint: Stream the entry set, sort by value, then collect. Concept: Using
Java Streams to sort entries.
• Q82. Generics example: Hint: Define class Box<T>{T value;} , and a generic method <T> T
first(T[] arr) . Concept: Compile-time type safety with generics.
• Q83. Optional usage: Hint: Use [Link](x).orElse(defaultVal) . Concept:
Avoiding null checks with Optional .
• Q84. Date formatting: Hint:
[Link]().format([Link]("yyyy-MM-dd")) . Concept: Java
8+ Date-Time API.
• Q85. Deadlock creation: Hint: Two threads each lock lockA then lockB (and vice versa). Concept:
Thread synchronization and deadlock conditions.

9
• Q86. Producer-Consumer: Hint: Use a blocking queue or wait/notify in shared buffer. Concept: Inter-
thread communication (e.g. BlockingQueue ).
• Q87. Synchronized example: Hint: Wrap shared resource access in synchronized(lock)
{ ... } . Concept: Mutual exclusion for thread safety.
• Q88. join() vs sleep(): Hint: join() waits for a thread to finish; sleep() pauses current thread.
Concept: Thread coordination vs delay.
• Q89. ConcurrentHashMap: Hint: Show updating map from multiple threads without explicit locks.
Concept: Thread-safe collections.
• Q90. Read file line by line: Hint: Use BufferedReader or [Link](Path) in try-with-
resources. Concept: I/O streams and resource management.
• Q91. Write file: Hint: Use BufferedWriter , PrintWriter , or [Link] . Concept: File I/O.
• Q92. Serialization: Hint: ObjectOutputStream to write, ObjectInputStream to read an object.
Concept: Java object serialization/deserialization.
• Q93. Try-with-resources: Hint: try (Resource res = ...) { ... } auto-closes. Concept:
Resource management and exception safety (Java 7+).
• Q94. Email regex: Hint: Pattern like ^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$ . Concept: Regular
expression for emails.
• Q95. Letters-only regex: Hint: Use matches("[a-zA-Z]+") . Concept: Regex character classes.
• Q96. Implement Stack: Hint: Use an array or ArrayList internally with push/pop. Concept: Classic
stack data structure (LIFO).
• Q97. Implement Queue: Hint: Use a linked list or circular array for FIFO. Concept: Classic queue data
structure (FIFO).
• Q98. Command-line args: Hint: Access String[] args in main and print. Concept: Java program
arguments.
• Q99. Palindrome integer: Hint: Reverse digits (without extra storage) or compare string. Concept:
Numeric palindrome check.
• Q100. Integer to binary: Hint: Repeatedly divide by 2 and collect remainders (or use
[Link] ). Concept: Manual base conversion.

Representative Solutions
Below are 20 full solutions (spread of topics/difficulty). Each includes runnable Java code and a brief
explanation. (All code targets Java 8+ compatibility.)

Q1. Reverse a string (Easy):

public class ReverseString {


public static String reverse(String s) {
if (s == null) throw new IllegalArgumentException("Null input");
return new StringBuilder(s).reverse().toString();
}
public static void main(String[] args) {
String input = "Interview";
[Link](reverse(input)); // Output: weivretnI

10
}
}

Explanation: We use [Link]() for brevity. This runs in Java 8+. The key concept is that
StringBuilder can efficiently build a reversed string【27†L1-L3】 (since String itself is immutable).

Q3. Check anagrams (Medium):

import [Link];
public class AnagramCheck {
public static boolean areAnagrams(String s1, String s2) {
if ([Link]() != [Link]()) return false;
char[] a = [Link]().toCharArray();
char[] b = [Link]().toCharArray();
[Link](a);
[Link](b);
return [Link](a, b);
}
public static void main(String[] args) {
[Link](areAnagrams("Listen", "Silent")); // true
[Link](areAnagrams("Hello", "World")); // false
}
}

Explanation: Sort both strings’ character arrays and compare. Sorting is O(n log n) . This tests string
manipulation and sorting. (Java version: any Java 8+.)

Q12. Rotate array by k (Medium):

import [Link];
public class RotateArray {
public static int[] rotate(int[] arr, int k) {
int n = [Link];
k %= n;
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[(i + k) % n] = arr[i];
}
return result;
}
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
[Link]([Link](rotate(arr, 2))); // [4,5,1,2,3]

11
}
}

Explanation: We compute the new index (i+k)%n for each element. This uses an extra array but is
straightforward. Concept: array index math.

Q19. Maximum subarray (Kadane) (Medium):

public class MaxSubarray {


public static int maxSubarraySum(int[] nums) {
int maxSoFar = nums[0], current = nums[0];
for (int i = 1; i < [Link]; i++) {
current = [Link](nums[i], current + nums[i]);
maxSoFar = [Link](maxSoFar, current);
}
return maxSoFar;
}
public static void main(String[] args) {
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
[Link](maxSubarraySum(arr)); // 6 (subarray [4, -1, 2, 1])
}
}

Explanation: We keep a running current sum and reset if it becomes negative. maxSoFar tracks the
best sum. Concept: Kadane’s algorithm (linear-time).

Q20. Spiral matrix (Medium):

import [Link].*;
public class SpiralPrint {
public static List<Integer> spiral(int[][] mat) {
List<Integer> result = new ArrayList<>();
int top=0, bottom=[Link]-1, left=0, right=mat[0].length-1;
while (top <= bottom && left <= right) {
for (int j = left; j <= right; j++) [Link](mat[top][j]);
top++;
for (int i = top; i <= bottom; i++) [Link](mat[i][right]);
right--;
if (top <= bottom) {
for (int j = right; j >= left; j--) [Link](mat[bottom][j]);
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) [Link](mat[i][left]);
left++;

12
}
}
return result;
}
public static void main(String[] args) {
int[][] mat = {{1,2,3},{4,5,6},{7,8,9}};
[Link](spiral(mat)); // [1,2,3,6,9,8,7,4,5]
}
}

Explanation: We walk the matrix boundaries in layers: top row L→R, right col T→B, bottom row R→L, left col
B→T. Concept: iterative simulation of spiral order.

Q22. Search rotated array (Hard):

public class SearchRotated {


public static int search(int[] arr, int target) {
int left=0, right=[Link]-1;
while (left <= right) {
int mid = (left + right) >>> 1;
if (arr[mid] == target) return mid;
// If left half is sorted
if (arr[left] <= arr[mid]) {
if (target >= arr[left] && target < arr[mid]) right = mid - 1;
else left = mid + 1;
} else { // right half is sorted
if (target > arr[mid] && target <= arr[right]) left = mid + 1;
else right = mid - 1;
}
}
return -1; // not found
}
public static void main(String[] args) {
int[] arr = {4,5,6,7,0,1,2};
[Link](search(arr, 0)); // 4
[Link](search(arr, 3)); // -1
}
}

Explanation: Classic modified binary search: at each step determine which half is sorted and decide where
target lies. Concept: binary search in a rotated array.

Q36. Reverse linked list (Medium):

13
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class ReverseLinkedList {
public static ListNode reverse(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode nextNode = [Link];
[Link] = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
// Utility to build list and print it
public static void main(String[] args) {
ListNode head = new ListNode(1);
[Link] = new ListNode(2); [Link] = new ListNode(3);
ListNode rev = reverse(head);
while (rev != null) { [Link]([Link] + " "); rev = [Link]; }
// Output: 3 2 1
}
}

Explanation: We iterate through the list, reversing the next pointers one by one. Concept: in-place linked-
list pointer manipulation.

Q37. Cycle detection (Hard):

public class LinkedListCycle {


public static boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && [Link] != null) {
slow = [Link];
fast = [Link];
if (slow == fast) return true;
}
return false;
}
public static void main(String[] args) {
ListNode head = new ListNode(3);
[Link] = new ListNode(2);
[Link] = new ListNode(0);

14
[Link] = new ListNode(-4);
[Link] = [Link]; // create cycle to node 2
[Link](hasCycle(head)); // true
}
}

Explanation: Floyd’s tortoise-and-hare algorithm: a slow pointer moves one step, fast moves two. If cycle
exists, they meet. Concept: two-pointer technique for cycle detection.

Q40. Check palindrome linked list (Medium):

import [Link];
public class PalindromeLinkedList {
public static boolean isPalindrome(ListNode head) {
if (head == null) return true;
Stack<Integer> stack = new Stack<>();
ListNode curr = head;
while (curr != null) { [Link]([Link]); curr = [Link]; }
curr = head;
while (curr != null) {
if ([Link] != [Link]()) return false;
curr = [Link];
}
return true;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
[Link] = new ListNode(2);
[Link] = new ListNode(1);
[Link](isPalindrome(head)); // true
}
}

Explanation: Push values onto a stack, then compare while popping. If all match, it’s a palindrome. Concept:
Using stack to compare forward/backwards.

Q41. Stack using two queues (Medium):

import [Link];
import [Link];
public class StackWithQueues {
private Queue<Integer> q1 = new LinkedList<>();
private Queue<Integer> q2 = new LinkedList<>();

public void push(int x) {

15
[Link](x);
while (![Link]()) [Link]([Link]());
// swap names
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
}
public int pop() {
return [Link]();
}
public static void main(String[] args) {
StackWithQueues stack = new StackWithQueues();
[Link](1); [Link](2); [Link](3);
[Link]([Link]()); // 3
[Link]([Link]()); // 2
}
}

Explanation: On push, enqueue new element into empty q2, pour all elements from q1 into q2, then swap
queues. Pop just dequeues. Concept: Emulate a LIFO stack using FIFO queues.

Q42. Queue using two stacks (Medium):

import [Link];
public class QueueWithStacks {
private Stack<Integer> stackIn = new Stack<>();
private Stack<Integer> stackOut = new Stack<>();

public void enqueue(int x) {


[Link](x);
}
public int dequeue() {
if ([Link]()) {
while (![Link]()) [Link]([Link]());
}
return [Link]() ? -1 : [Link]();
}
public static void main(String[] args) {
QueueWithStacks q = new QueueWithStacks();
[Link](10); [Link](20); [Link](30);
[Link]([Link]()); // 10
[Link]([Link]()); // 20
}
}

16
Explanation: enqueue pushes to stackIn . On dequeue , if stackOut is empty, transfer all from
stackIn to stackOut (reversing order), then pop. Concept: Use two stacks to model FIFO.

Q55. Binary Search (Easy):

public class BinarySearchExample {


public static int binarySearch(int[] arr, int key) {
int lo = 0, hi = [Link] - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
if (arr[mid] == key) return mid;
else if (arr[mid] < key) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1,3,5,7,9};
[Link](binarySearch(arr, 7)); // 3
[Link](binarySearch(arr, 4)); // -1
}
}

Explanation: Standard binary search on sorted array. Uses bitwise unsigned shift >>> to avoid overflow
(Java 8+). Concept: divide-and-conquer search.

Q56. Merge Sort (Hard):

import [Link];
public class MergeSortExample {
public static void mergeSort(int[] arr) {
if ([Link] <= 1) return;
int mid = [Link] / 2;
int[] left = [Link](arr, 0, mid);
int[] right = [Link](arr, mid, [Link]);
mergeSort(left);
mergeSort(right);
merge(arr, left, right);
}
private static void merge(int[] arr, int[] left, int[] right) {
int i=0, j=0, k=0;
while (i < [Link] && j < [Link]) {
arr[k++] = (left[i] <= right[j]) ? left[i++] : right[j++];
}
while (i < [Link]) arr[k++] = left[i++];

17
while (j < [Link]) arr[k++] = right[j++];
}
public static void main(String[] args) {
int[] arr = {5,2,4,6,1,3};
mergeSort(arr);
[Link]([Link](arr)); // [1,2,3,4,5,6]
}
}

Explanation: Recursively split the array and merge sorted halves. Concept: classic divide-and-conquer (n log
n) sorting.

Q57. Quick Sort (Hard):

import [Link];
public class QuickSortExample {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int p = partition(arr, low, high);
quickSort(arr, low, p - 1);
quickSort(arr, p + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
i++;
}
}
// swap pivot to correct place
int temp = arr[i]; arr[i] = arr[high]; arr[high] = temp;
return i;
}
public static void main(String[] args) {
int[] arr = {4,2,7,1,3};
quickSort(arr, 0, [Link]-1);
[Link]([Link](arr)); // [1,2,3,4,7]
}
}

Explanation: Pick the last element as pivot, partition the array around it, then sort subarrays. Concept: in-
place recursive quicksort.

18
Q79. Lambda sort (Easy):

import [Link].*;
public class LambdaSort {
public static void main(String[] args) {
List<String> names = [Link]("Alice", "Bob", "Charly");
// sort by string length using lambda
[Link]((a, b) -> [Link]([Link](), [Link]()));
[Link](names); // [Bob, Alice, Charly]
}
}

Explanation: We use [Link] with a lambda comparator. Concept: Java 8 lambdas simplify sorting logic.

Q80. Stream filter and map (Medium):

import [Link].*;
import [Link].*;
public class StreamExample {
public static void main(String[] args) {
List<Integer> nums = [Link](-2, 3, -1, 4, 0);
// Filter positives and square them
List<Integer> result = [Link]()
.filter(x -> x > 0)
.map(x -> x * x)
.collect([Link]());
[Link](result); // [9, 16]
}
}

Explanation: We build a stream from nums , apply filter and map , and collect results. Concept: fluent
stream operations (Java 8+).

Q85. Deadlock scenario (Hard):

public class DeadlockDemo {


static class Friend {
private final String name;
public Friend(String name) { [Link] = name; }
public synchronized void bow(Friend other) {
[Link](name + " bowing to " + [Link]);
[Link](this);
}
public synchronized void rise(Friend other) {

19
[Link](name + " rising after " + [Link] + "
bowed.");
}
}
public static void main(String[] args) {
final Friend a = new Friend("Alice");
final Friend b = new Friend("Bob");
// Thread 1: Alice bows to Bob
new Thread(() -> [Link](b)).start();
// Thread 2: Bob bows to Alice (simultaneously)
new Thread(() -> [Link](a)).start();
// Possible deadlock: each thread holds one lock and waits on the other.
}
}

Explanation: We simulate deadlock by having [Link](Bob) and [Link](Alice) on separate


threads. Each holds its own lock and tries to acquire the other’s, causing a deadlock. Concept: thread
synchronization locks leading to deadlock.

Q86. Producer-Consumer (Hard):

import [Link].*;
public class ProducerConsumerDemo {
public static void main(String[] args) {
BlockingQueue<Integer> buffer = new ArrayBlockingQueue<>(5);
// Producer
Runnable producer = () -> {
for(int i = 1; i <= 5; i++) {
try {
[Link](i);
[Link]("Produced " + i);
} catch (InterruptedException e) {
[Link]().interrupt(); }
}
};
// Consumer
Runnable consumer = () -> {
for(int i = 1; i <= 5; i++) {
try {
int val = [Link]();
[Link]("Consumed " + val);
} catch (InterruptedException e) {
[Link]().interrupt(); }
}
};
new Thread(producer).start();

20
new Thread(consumer).start();
}
}

Explanation: We use a BlockingQueue to safely pass data between producer/consumer threads. This
avoids explicit wait/notify. Concept: thread-safe buffer (Java 8+ [Link] ).

Q90. Read file line by line (Easy):

import [Link].*;
public class ReadFileExample {
public static void main(String[] args) {
// Suppose "[Link]" exists in working directory
try (BufferedReader reader = new BufferedReader(new
FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}
}
}

Explanation: Uses BufferedReader in a try-with-resources to auto-close. Concept: classic I/O for text files.

Q92. Serialize/Deserialize an object (Medium):

import [Link].*;
// A sample serializable class
class Person implements Serializable {
private String name;
public Person(String n) { name = n; }
public String toString() { return "Person{name='" + name + "'}"; }
}
public class SerializationDemo {
public static void main(String[] args) {
Person p = new Person("Alice");
// Serialize
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("[Link]"))) {
[Link](p);
} catch (IOException e) { [Link](); }
// Deserialize

21
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("[Link]"))) {
Person p2 = (Person) [Link]();
[Link](p2); // Person{name='Alice'}
} catch (IOException | ClassNotFoundException e) {
[Link](); }
}
}

Explanation: We write the Person object to a file via ObjectOutputStream and read it back. Concept:
Java serialization (make class implement Serializable ).

Follow-Up Variants (30 examples)


• Q1: Extend to reverse words in a sentence, or reverse in place using char array.
• Q2: Find the longest palindromic substring in a string (e.g. expand-around-center).
• Q3: Group a list of strings into anagram clusters (return list of lists).
• Q4: Find the first non-repeating character (use HashMap).
• Q5: Remove consonants instead (keep vowels only).
• Q8: URLify with additional constraints (e.g. trailing spaces).
• Q10: Validate phone numbers or IP addresses with regex.
• Q12: Rotate a linked list by k places instead of array.
• Q14: Find the k-th largest element (use a heap or quickselect).
• Q18: 3-sum problem (find three indices with given sum).
• Q19: Minimum subarray sum or circular array max sum.
• Q20: Print matrix in anti-spiral order.
• Q22: Find the rotation count (index of smallest element) in rotated array.
• Q36: Reverse a linked list in chunks of size k.
• Q37: Return the node where the cycle begins in a linked list.
• Q41: Implement stack with a single queue.
• Q42: Implement queue with only one stack (amortized).
• Q46: Morris inorder traversal (no recursion/stack).
• Q47: Transform a binary tree into a BST (same structure).
• Q51: Find shortest path length in an unweighted graph (BFS variant).
• Q52: Check if a graph is a DAG.
• Q53: If graph has multiple valid topological orders, return any one.
• Q55: Find first occurrence of target in sorted array (binary search variant).
• Q56: Implement iterative (bottom-up) merge sort.
• Q60: Sieve of Eratosthenes for all primes up to n.
• Q67: Compute LIS in O(n log n) time (Patience sorting method).
• Q72: Demonstrate final classes or method overriding rules.
• Q79: Sort with different comparator (reverse alphabetical).
• Q80: Use parallel stream and compare performance.
• Q85: Modify code to avoid deadlock (e.g. enforce lock ordering).
• Q90: Read a file using [Link] ( [Link] ) or Scanner .

22
Recommended Resources
• Oracle Java Documentation & Tutorials – Official guides on language features and libraries (e.g.
Java™ Tutorials on Collections, Streams, etc.)【26†L73-L80】【19†L74-L77】.
• OpenJDK Project – Source code and updates for the Java platform ([Link]).
• Effective Java (Joshua Bloch) – Widely cited best practices for Java (a top Java book)【30†L61-L69】.
• LeetCode – Extensive collection of coding problems and discussions (widely used for interview prep)
【32†L1-L2】.
• GeeksforGeeks – Large repository of articles and practice problems on Java and algorithms
【34†L29-L32】.

Each question above tests a core concept: for instance, many string problems use StringBuilder (since
String is immutable【27†L1-L3】), sorting tasks rely on [Link]() , and concurrency questions
emphasize thread coordination. By practicing these questions and understanding the outlined hints, you
should build strong Java interview readiness.

23

You might also like