200 Java DSA Questions and Answers
Arrays
1. Find the largest element in an array
public int findLargest(int[] arr) {
int max = arr[0];
for (int num : arr) {
if (num > max) {
max = num;
}
}
return max;
}
2. Reverse an array
public void reverseArray(int[] arr) {
int left = 0, right = arr.length - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
Linked Lists
3. Detect a cycle in a linked list
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
4. Reverse a linked list
public ListNode reverseList(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
Stacks and Queues
5. Implement a stack using an array
class Stack {
private int[] arr;
private int top;
public Stack(int size) {
arr = new int[size];
top = -1;
}
public void push(int val) {
if (top == arr.length - 1) throw new StackOverflowError();
arr[++top] = val;
}
public int pop() {
if (top == -1) throw new IllegalStateException("Stack is empty");
return arr[top--];
}
}
6. Implement a queue using two stacks
class QueueUsingStack {
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
public void enqueue(int x) {
s1.push(x);
}
public int dequeue() {
if (s2.isEmpty()) {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
}
return s2.isEmpty() ? -1 : s2.pop();
}
}