0% found this document useful (0 votes)
7 views8 pages

Dsa Programs

The document provides a series of Java interview questions focused on fundamental Data Structures and Algorithms, including implementations for a Stack, Queue, Binary Search Tree, Graph with BFS, and Merge Sort. Each section includes a question, a Java code implementation, and an explanation of how the data structure or algorithm works. It emphasizes the importance of understanding time and space complexity, as well as the ability to explain one's code during interviews.

Uploaded by

pavankolla1020
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)
7 views8 pages

Dsa Programs

The document provides a series of Java interview questions focused on fundamental Data Structures and Algorithms, including implementations for a Stack, Queue, Binary Search Tree, Graph with BFS, and Merge Sort. Each section includes a question, a Java code implementation, and an explanation of how the data structure or algorithm works. It emphasizes the importance of understanding time and space complexity, as well as the ability to explain one's code during interviews.

Uploaded by

pavankolla1020
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
You are on page 1/ 8

Okay, to be clear, you'd like me to provide Java interview questions that specifically test your

knowledge of fundamental Data Structures and Algorithms, beyond just arrays and strings. Let's
cover some key areas:

Data Structures & Algorithms (DSA) Programs in Java


Interviews
Here are some common DSA-based programming questions in Java interviews:
1. Implement a Stack using an Array or Linked List:
●​ Question: Implement a stack data structure with push, pop, peek, and isEmpty
operations using either an array or a linked list in Java.
●​ Answer (Java - using Array):​
class ArrayStack {​
private int[] array;​
private int top;​
private int capacity;​

public ArrayStack(int capacity) {​
this.capacity = capacity;​
this.array = new int[capacity];​
this.top = -1;​
}​

public void push(int data) {​
if (top == capacity - 1) {​
System.out.println("Stack Overflow");​
return;​
}​
array[++top] = data;​
}​

public int pop() {​
if (isEmpty()) {​
System.out.println("Stack Underflow");​
return Integer.MIN_VALUE; // Or throw an exception​
}​
return array[top--];​
}​

public int peek() {​
if (isEmpty()) {​
System.out.println("Stack is empty");​
return Integer.MIN_VALUE; // Or throw an exception​
}​
return array[top];​
}​

public boolean isEmpty() {​
return top == -1;​
}​

public static void main(String[] args) {​
ArrayStack stack = new ArrayStack(5);​
stack.push(10);​
stack.push(20);​
System.out.println("Peek: " + stack.peek()); // Output: 20​
System.out.println("Pop: " + stack.pop()); // Output: 20​
System.out.println("Is empty: " + stack.isEmpty()); //
Output: false​
}​
}​

●​ Explanation: This implementation uses a fixed-size array. top tracks the index of the top
element. push adds an element to the top, pop removes and returns the top element,
peek returns the top element without removing it, and isEmpty checks if the stack is
empty.
2. Implement a Queue using an Array or Linked List:
●​ Question: Implement a queue data structure with enqueue, dequeue, peek, and isEmpty
operations using either an array or a linked list in Java.
●​ Answer (Java - using Linked List):​
class Node {​
int data;​
Node next;​
Node(int data) {​
this.data = data;​
this.next = null;​
}​
}​

class LinkedListQueue {​
private Node front;​
private Node rear;​

public LinkedListQueue() {​
this.front = null;​
this.rear = null;​
}​

public void enqueue(int data) {​
Node newNode = new Node(data);​
if (rear == null) {​
front = rear = newNode;​
return;​
}​
rear.next = newNode;​
rear = newNode;​
}​

public int dequeue() {​
if (front == null) {​
System.out.println("Queue is empty");​
return Integer.MIN_VALUE; // Or throw an exception​
}​
int data = front.data;​
front = front.next;​
if (front == null) {​
rear = null;​
}​
return data;​
}​

public int peek() {​
if (front == null) {​
System.out.println("Queue is empty");​
return Integer.MIN_VALUE; // Or throw an exception​
}​
return front.data;​
}​

public boolean isEmpty() {​
return front == null;​
}​

public static void main(String[] args) {​
LinkedListQueue queue = new LinkedListQueue();​
queue.enqueue(10);​
queue.enqueue(20);​
System.out.println("Peek: " + queue.peek()); // Output:
10​
System.out.println("Dequeue: " + queue.dequeue()); //
Output: 10​
System.out.println("Is empty: " + queue.isEmpty()); //
Output: false​
}​
}​

●​ Explanation: This implementation uses a singly linked list. front points to the beginning of
the queue, and rear points to the end. enqueue adds to the rear, dequeue removes from
the front, peek returns the front element, and isEmpty checks if the queue is empty.
3. Implement a Binary Search Tree (BST) with Search, Insert, and Delete Operations:
●​ Question: Implement a Binary Search Tree in Java with methods to search for a value,
insert a new value, and delete an existing value.
●​ Answer (Java):​
class TreeNode {​
int val;​
TreeNode left, right;​
TreeNode(int val) {​
this.val = val;​
this.left = this.right = null;​
}​
}​

class BinarySearchTree {​
TreeNode root;​

public TreeNode search(TreeNode root, int key) {​
if (root == null || root.val == key)​
return root;​
if (key < root.val)​
return search(root.left, key);​
return search(root.right, key);​
}​

public void insert(int key) {​
root = insertRec(root, key);​
}​

private TreeNode insertRec(TreeNode root, int key) {​
if (root == null) {​
root = new TreeNode(key);​
return root;​
}​
if (key < root.val)​
root.left = insertRec(root.left, key);​
else if (key > root.val)​
root.right = insertRec(root.right, key);​
return root;​
}​

public void delete(int key) {​
root = deleteRec(root, key);​
}​

private TreeNode deleteRec(TreeNode root, int key) {​
if (root == null)​
return root;​

if (key < root.val)​
root.left = deleteRec(root.left, key);​
else if (key > root.val)​
root.right = deleteRec(root.right, key);​
else {​
// Node with only one child or no child​
if (root.left == null)​
return root.right;​
else if (root.right == null)​
return root.left;​

// Node with two children: Get the inorder successor
(smallest in the right subtree)​
root.val = minValue(root.right);​

// Delete the inorder successor​
root.right = deleteRec(root.right, root.val);​
}​
return root;​
}​

private int minValue(TreeNode root) {​
int minv = root.val;​
while (root.left != null) {​
minv = root.left.val;​
root = root.left;​
}​
return minv;​
}​

public static void main(String[] args) {​
BinarySearchTree bst = new BinarySearchTree();​
bst.insert(50);​
bst.insert(30);​
bst.insert(20);​
bst.insert(40);​
bst.insert(70);​
bst.insert(60);​
bst.insert(80);​

System.out.println("Search 40: " + (bst.search(bst.root,
40) != null)); // Output: true​
bst.delete(30);​
System.out.println("Search 30 after delete: " +
(bst.search(bst.root, 30) != null)); // Output: false​
}​
}​

●​ Explanation: This implements a basic BST. search recursively finds a node with a given
key. insert adds a new node while maintaining the BST property. delete handles cases
with no child, one child, and two children (using the inorder successor).
4. Implement a Basic Graph and Perform Breadth-First Search (BFS) or Depth-First
Search (DFS):
●​ Question: Implement a graph using an adjacency list in Java and perform either
Breadth-First Search (BFS) or Depth-First Search (DFS) starting from a given node.
●​ Answer (Java - BFS):​
import java.util.*;​

class Graph {​
private int V; // Number of vertices​
private LinkedList<Integer>[] adj; // Adjacency list​

Graph(int v) {​
V = v;​
adj = new LinkedList[v];​
for (int i = 0; i < v; ++i)​
adj[i] = new LinkedList<>();​
}​

void addEdge(int v, int w) {​
adj[v].add(w); // Add w to v's list.​
}​

void BFS(int s) {​
boolean[] visited = new boolean[V];​
LinkedList<Integer> queue = new LinkedList<>();​

visited[s] = true;​
queue.add(s);​

while (queue.size() != 0) {​
s = queue.poll();​
System.out.print(s + " ");​

Iterator<Integer> i = adj[s].listIterator();​
while (i.hasNext()) {​
int n = i.next();​
if (!visited[n]) {​
visited[n] = true;​
queue.add(n);​
}​
}​
}​
}​

public static void main(String[] args) {​
Graph g = new Graph(4);​
g.addEdge(0, 1);​
g.addEdge(0, 2);​
g.addEdge(1, 2);​
g.addEdge(2, 0);​
g.addEdge(2, 3);​
g.addEdge(3, 3);​

System.out.println("Breadth First Traversal starting from
vertex 2:");​
g.BFS(2); // Output: 2 0 3 1​
}​
}​

●​ Explanation: This implements a graph using an adjacency list. The BFS method starts a
BFS from a given source node s. It uses a visited array to keep track of visited nodes and
a Queue for the BFS traversal.
5. Implement a Sorting Algorithm (e.g., Merge Sort or Quick Sort):
●​ Question: Implement the Merge Sort algorithm in Java.
●​ Answer (Java - Merge Sort):​
class MergeSort {​
void merge(int[] arr, int l, int m, int r) {​
int n1 = m - l + 1;​
int n2 = r - m;​

int[] L = new int[n1];​
int[] R = new int[n2];​

for (int i = 0; i < n1; ++i)​
L[i] = arr[l + i];​
for (int j = 0; j < n2; ++j)​
R[j] = arr[m + 1 + j];​

int i = 0, j = 0, k = l;​
while (i < n1 && j < n2) {​
if (L[i] <= R[j]) {​
arr[k++] = L[i++];​
} else {​
arr[k++] = R[j++];​
}​
}​

while (i < n1) {​
arr[k++] = L[i++];​
}​

while (j < n2) {​
arr[k++] = R[j++];​
}​
}​

void sort(int[] arr, int l, int r) {​
if (l < r) {​
int m = l + (r - l) / 2;​
sort(arr, l, m);​
sort(arr, m + 1, r);​
merge(arr, l, m, r);​
}​
}​

public static void main(String[] args) {​
int[] arr = {12, 11, 13, 5, 6, 7};​
MergeSort ob = new MergeSort();​
ob.sort(arr, 0, arr.length - 1);​
System.out.println("Sorted array:");​
for (int i : arr) System.out.print(i + " "); // Output: 5
6 7 11 12 13​
}​
}​

●​ Explanation: Merge Sort is a divide and conquer algorithm. The sort method recursively
divides the array into halves until the base case (single element). The merge method then
merges the sorted halves.
When you are asked these kinds of questions, the interviewer is often interested in:
●​ Your ability to implement fundamental data structures and algorithms from scratch.
●​ Your understanding of the time and space complexity of the operations.
●​ Your problem-solving approach.
Make sure you can explain your code and the reasoning behind your choices.
Would you like to explore other DSA program examples?

You might also like