practical and interview questions - ashish-ghub/docs GitHub Wiki
-
Which data structure is suitable for implementing a LIFO (Last-In, First-Out) behavior?
{a) Queue b) ((Stack)) c) LinkedList d) HashMap}
-
Which data structure provides constant-time complexity for search, insertion, and deletion of elements?
a) LinkedList b) TreeSet c) ((HashMap)) d) ArrayList
-
Which data structure is used to efficiently store key-value pairs?
a) LinkedList b) HashSet c) TreeMap d) ((HashMap))
-
What is the purpose of the synchronized keyword in Java?
a) It prevents the creation of multiple threads. b) ((*It ensures that only one thread can access a shared resource at a time.*)) c) It increases the performance of multithreaded programs. d) It enables parallel execution of threads.
-
Which concurrent collection class in Java provides a thread-safe implementation of a queue?
a) ArrayList b) PriorityQueue c) ((LinkedBlockingQueue)) d) HashSet
-
What is a deadlock in Java concurrency?
a) It occurs when a thread is waiting indefinitely for a lock or resource that is held by another thread. b) It happens when multiple threads access a shared resource simultaneously. c) It refers to the termination of a thread without completing its task. d) It occurs when a thread is terminated forcibly by an external process.
-
Which Java API is commonly used for creating and consuming RESTful web services?
a) JDBC b) RMI c) JMS d) JAX-RS
-
What is the purpose of serialization in Java distributed systems?
a) It is used for encrypting network communications. b) ((*It allows objects to be converted into a stream of bytes for transmission over a network.*)) c) It ensures that distributed systems are fault-tolerant. d) It enables load balancing in distributed systems.
-
Which Java library is commonly used for remote method invocation?
a) JAXB b) JAX-WS c) RMI d) JMS
-
What is the purpose of distributed caching in Java distributed systems?
a) It allows for efficient data replication across multiple servers. b) It provides fault tolerance and high availability of data. c) ((*It enables load balancing and improves performance.*)) d) It ensures secure communication between distributed components.
Answers:
-
b) Stack
-
c) HashMap
-
d) HashMap
-
b) It ensures that only one thread can access a shared resource at a time.
-
c) LinkedBlockingQueue
-
a) It occurs when a thread is waiting indefinitely for a lock or resource that is held by another thread.
-
d) JAX-RS
-
b) It allows objects to be converted into a stream of bytes for transmission over a network.
-
c) RMI
-
c) It enables load balancing and improves performance.
www.interviewbit.com/coding-interview-questions/
For an array {3, 2, 1, 5, 6, 4} and k = 2, the output will be:
csharp Copy code The 2th largest element is 5
public class KthLargestElement {
public static int findKthLargest(int[] nums, int k) { // Min-heap with size k to store the k largest elements PriorityQueue<Integer> minHeap = new PriorityQueue<>(k); // Iterate through the array for (int num : nums) { minHeap.offer(num); // Add current element to the heap if (minHeap.size() > k) { // If heap size exceeds k, remove the smallest element minHeap.poll(); } } // The root of the heap will be the Kth largest element return minHeap.peek(); } public static void main(String[] args) { int[] nums = {3, 2, 1, 5, 6, 4}; int k = 2; System.out.println("The " + k + "th largest element is " + findKthLargest(nums, k)); }
}
Problem 1: Reverse a Linked List Write a function to reverse a singly linked list.
Solution:
class ListNode {
int val; ListNode next; ListNode(int val) { this.val = val; }
} public class ReverseLinkedList {
public ListNode reverse(ListNode head) { ListNode prev = null; ListNode current = head; while (current != null) { ListNode next = current.next; current.next = prev; prev = current; current = next; } return prev; }
}
Problem 2: Find the Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters.
Solution:
import java.util.HashSet;
public class LongestSubstring {
public int lengthOfLongestSubstring(String s) { int maxLength = 0; int start = 0; int end = 0; HashSet<Character> set = new HashSet<>(); while (end < s.length()) { if (!set.contains(s.charAt(end))) { set.add(s.charAt(end)); maxLength = Math.max(maxLength, end - start + 1); end++; } else { set.remove(s.charAt(start)); start++; } } return maxLength; }
}
Problem 3: Find the Two Sum Given an array of integers, return indices of the two numbers such that they add up to a specific target.
Solution:
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public 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 found."); }
} Problem 4: Finding the Longest Increasing Subarray Write a Java method that takes an array of integers as input and returns the longest increasing subarray within the given array. An increasing subarray is defined as a contiguous portion of the array where the elements are in strictly increasing order.
Solution:
public class LongestIncreasingSubarray {
public static int[] findLongestIncreasingSubarray(int[] nums) { if (nums == null || nums.length == 0) return new int[0]; int maxLength = 1; int currentLength = 1; int endIndex = 0; for (int i = 1; i < nums.length; i++) { if (nums[i] > nums[i - 1]) { currentLength++; } else { if (currentLength > maxLength) { maxLength = currentLength; endIndex = i - 1; } currentLength = 1; } } if (currentLength > maxLength) { maxLength = currentLength; endIndex = nums.length - 1; } int startIndex = endIndex - maxLength + 1; return Arrays.copyOfRange(nums, startIndex, endIndex + 1); } public static void main(String[] args) { int[] nums = {1, 3, 2, 4, 7, 6, 8}; int[] result = findLongestIncreasingSubarray(nums); System.out.println("Longest Increasing Subarray: " + Arrays.toString(result)); }
} Problem 5: Finding the Missing Number Given an array containing n distinct numbers taken from 0 to n, write a Java method to find the missing number.
public class MissingNumber {
public static int findMissingNumber(int[] nums) { int n = nums.length; int sum = 0; for (int num : nums) { sum += num; } int expectedSum = n * (n + 1) / 2; return expectedSum - sum; } public static void main(String[] args) { int[] nums = {0, 1, 3, 4, 5}; int missingNumber = findMissingNumber(nums); System.out.println("Missing Number: " + missingNumber); }
}
Problem 6: Check if Strings are Anagrams Write a Java method to check if two strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of another word or phrase.
Solution:
public class AnagramCheck {
public static boolean areAnagrams(String str1, String str2) { if (str1.length() != str2.length()) return false; int[] count = new int[26]; // Assuming lowercase English alphabet for (int i = 0; i < str1.length(); i++) { count[str1.charAt(i) - 'a']++; count[str2.charAt(i) - 'a']--; } for (int i = 0; i < 26; i++) { if (count[i] != 0) return false; } return true; } public static void main(String[] args) { String str1 = "listen"; String str2 = "silent"; boolean areAnagrams = areAnagrams(str1, str2); System.out.println("Are Anagrams: " + areAnagrams);
} Problem 7: Find the Longest Increasing Subsequence Given an array of integers, find the length of the longest increasing subsequence.
Solution:
public class LongestIncreasingSubsequence {
public static int findLongestIncreasingSubsequence(int[] nums) { if (nums == null || nums.length == 0) return 0; int[] dp = new int[nums.length]; dp[0] = 1; int maxLength = 1; for (int i = 1; i < nums.length; i++) { dp[i] = 1; for (int j = 0; j < i; j++) { if (nums[i] > nums[j]) dp[i] = Math.max(dp[i], dp[j] + 1); } maxLength = Math.max(maxLength, dp[i]); } return maxLength; } public static void main(String[] args) { int[] nums = {10, 9, 2, 5, 3, 7, 101, 18}; int length = findLongestIncreasingSubsequence(nums); System.out.println("Length of the longest increasing subsequence: " + length); }
} Problem 8: Kth Largest Element in an Array Find the kth largest element in an unsorted array.
int[] nums = {3, 2, 1, 5, 6, 4};
k=2 → 5
Solution:
import java.util.PriorityQueue;
public class KthLargestElement {
public 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(); }
} Problem 9: Subarray Sum Equals K Given an array of integers, find the total number of continuous subarrays whose sum equals a specific target
Solution:
import java.util.HashMap;
public class SubarraySumEqualsK {
public int subarraySum(int[] nums, int k) { int count = 0; int sum = 0; HashMap<Integer, Integer> sumFrequency = new HashMap<>(); sumFrequency.put(0, 1); for (int num : nums) { sum += num; if (sumFrequency.containsKey(sum - k)) { count += sumFrequency.get(sum - k); } sumFrequency.put(sum, sumFrequency.getOrDefault(sum, 0) + 1); } return count; }
}
Concurrency Problem 1: Print Even and Odd Numbers Using Threads Write a Java program to print even and odd numbers alternatively using two separate threads.
Solution:
class Printer {
private int maxNumber; private volatile int currentNumber = 1; public Printer(int maxNumber) { this.maxNumber = maxNumber; } public void printEven() { synchronized (this) { while (currentNumber <= maxNumber) { if (currentNumber % 2 == 0) { System.out.println("Even: " + currentNumber); currentNumber++; notify(); } else { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public void printOdd() { synchronized (this) { while (currentNumber <= maxNumber) { if (currentNumber % 2 != 0) { System.out.println("Odd: " + currentNumber); currentNumber++; notify(); } else { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
}
public class EvenOddPrinter {
public static void main(String[] args) { Printer printer = new Printer(10); Thread evenThread = new Thread(printer::printEven); Thread oddThread = new Thread(printer::printOdd); evenThread.start(); oddThread.start(); }
} Problem 2: Producer-Consumer Problem Implement the producer-consumer problem using threads and a shared buffer.
Solution:
import java.util.LinkedList; import java.util.Queue;
class Buffer {
private Queue<Integer> queue; private int maxSize; public Buffer(int maxSize) { this.maxSize = maxSize; this.queue = new LinkedList<>(); } public void produce(int value) throws InterruptedException { synchronized (this) { while (queue.size() == maxSize) { wait(); } queue.add(value); System.out.println("Produced: " + value); notify(); } } public void consume() throws InterruptedException { synchronized (this) { while (queue.isEmpty()) { wait(); } int value = queue.poll(); System.out.println("Consumed: " + value); notify(); } }
}
public class ProducerConsumer {
public static void main(String[] args) { Buffer buffer = new Buffer(5); Thread producerThread = new Thread(() -> { try { for (int i = 1; i <= 10; i++) { buffer.produce(i); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } }); Thread consumerThread = new Thread(() -> { try { for (int i = 1; i <= 10; i++) { buffer.consume(); Thread.sleep(2000); } } catch (InterruptedException e) { e.printStackTrace(); } }); producerThread.start(); consumerThread.start(); }
} Problem 3: Dining Philosophers Problem Implement the dining philosophers problem using threads in Java. There are multiple philosophers sitting at a table, and there are forks between each pair of philosophers. To eat, a philosopher needs to acquire both the left and right forks. However, if all philosophers simultaneously pick up their left forks, they will be deadlocked. Implement a solution to avoid deadlock.
Solution:
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;
class Philosopher implements Runnable {
private int id; private Lock leftFork; private Lock rightFork; public Philosopher(int id, Lock leftFork, Lock rightFork) { this.id = id; this.leftFork = leftFork; this.rightFork = rightFork; } public void run() { try { while (true) { think(); eat(); } } catch (InterruptedException e) { e.printStackTrace(); } } private void think() throws InterruptedException { System.out.println("Philosopher " + id + " is thinking"); Thread.sleep((long) (Math.random() * 1000)); } private void eat() throws InterruptedException { leftFork.lock(); rightFork.lock(); System.out.println("Philosopher " + id + " is eating"); Thread.sleep((long) (Math.random() * 1000)); rightFork.unlock(); leftFork.unlock(); }
}
public class DiningPhilosophersProblem {
public static void main(String[] args) { int numPhilosophers = 5; Lock[] forks = new ReentrantLock[numPhilosophers]; for (int i = 0; i < numPhilosophers; i++) { forks[i] = new ReentrantLock(); } Thread[] philosophers = new Thread[numPhilosophers]; for (int i = 0; i < numPhilosophers; i++) { Lock leftFork = forks[i]; Lock rightFork = forks[(i + 1) % numPhilosophers]; philosophers[i] = new Thread(new Philosopher(i, leftFork, rightFork)); philosophers[i].start(); } }
}
((*Problem 4: Print Numbers Sequentially*)) ((*Write a Java program to print numbers from 1 to 10 sequentially using three threads. The first thread prints “1”, the second thread prints “2”, and so on.*))
Solution:
class PrintNumber implements Runnable {
private static final Object lock = new Object(); private static int number = 1; private int threadId; private int totalThreads; public PrintNumber(int threadId, int totalThreads) { this.threadId = threadId; this.totalThreads = totalThreads; } @Override public void run() { while (number <= 10) { synchronized (lock) { while (number % totalThreads != threadId) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Thread " + threadId + ": " + number); number++; lock.notifyAll(); } } }
}
public class PrintNumbersSequentially {
public static void main(String[] args) { int totalThreads = 3; Thread[] threads = new Thread[totalThreads]; for (int i = 0; i < totalThreads; i++) { threads[i] = new Thread(new PrintNumber(i, totalThreads)); threads[i].start(); } for (int i = 0; i < totalThreads; i++) { try { threads[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } }
} Problem 5: Distributed Task Processing Implement a distributed task processing system where multiple tasks can be submitted to a pool of worker nodes for processing. The system should distribute the tasks evenly among the workers and ensure fault tolerance.
Solution:
import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
// Task class representing a unit of work class Task {
private String id; // Other task data and methods public Task(String id) { this.id = id; } public void process() { // Implement logic to process the task }
}
// Worker class representing a worker node in the distributed system class Worker extends Thread {
private BlockingQueue<Task> taskQueue; public Worker(BlockingQueue<Task> taskQueue) { this.taskQueue = taskQueue; } @Override public void run() { while (true) { try { Task task = taskQueue.take(); // Take a task from the queue task.process(); // Process the task } catch (InterruptedException e) { e.printStackTrace(); } } }
}
// Distributed task processing system class class DistributedTaskProcessingSystem {
private List<Worker> workers; private BlockingQueue<Task> taskQueue; public DistributedTaskProcessingSystem(int numWorkers) { this.workers = new ArrayList<>(); this.taskQueue = new LinkedBlockingQueue<>(); // Create worker threads and start them for (int i = 0; i < numWorkers; i++) { Worker worker = new Worker(taskQueue); workers.add(worker); worker.start(); } } public void submitTask(Task task) { taskQueue.add(task); // Add the task to the task queue }
}
// Usage example public class DistributedTaskProcessingExample {
public static void main(String[] args) { // Create a distributed task processing system with 3 workers DistributedTaskProcessingSystem taskProcessingSystem = new DistributedTaskProcessingSystem(3); // Submit tasks to the system Task task1 = new Task("Task1"); Task task2 = new Task("Task2"); Task task3 = new Task("Task3"); taskProcessingSystem.submitTask(task1); taskProcessingSystem.submitTask(task2); taskProcessingSystem.submitTask(task3); }
}
Serialization / XML /JSON Processing Problem 1: Custom Serialization Implement a custom serialization and deserialization mechanism for a complex object that contains nested objects. The custom serialization should allow the object and its nested objects to be serialized and deserialized correctly.
Solution:
import java.io.*;
class ComplexObject implements Serializable {
private int id; private String name; private NestedObject nestedObject; public ComplexObject(int id, String name, NestedObject nestedObject) { this.id = id; this.name = name; this.nestedObject = nestedObject; } private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); // Perform custom serialization for nestedObject oos.writeObject(nestedObject.getProperty1()); oos.writeObject(nestedObject.getProperty2()); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); // Perform custom deserialization for nestedObject String property1 = (String) ois.readObject(); int property2 = (int) ois.readObject(); nestedObject = new NestedObject(property1, property2); } // Getters and setters
}
class NestedObject {
private String property1; private int property2; public NestedObject(String property1, int property2) { this.property1 = property1; this.property2 = property2; } // Getters and setters
}
public class CustomSerializationExample {
public static void main(String[] args) { ComplexObject object = new ComplexObject(1, "Object", new NestedObject("Property 1", 10)); try (FileOutputStream fileOutputStream = new FileOutputStream("object.ser"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) { objectOutputStream.writeObject(object); System.out.println("Object serialized successfully."); } catch (IOException e) { e.printStackTrace(); } try (FileInputStream fileInputStream = new FileInputStream("object.ser"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) { ComplexObject deserializedObject = (ComplexObject) objectInputStream.readObject(); System.out.println("Object deserialized successfully."); System.out.println("ID: " + deserializedObject.getId()); System.out.println("Name: " + deserializedObject.getName()); System.out.println("Nested Object Property 1: " + deserializedObject.getNestedObject().getProperty1()); System.out.println("Nested Object Property 2: " + deserializedObject.getNestedObject().getProperty2()); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } }
} Problem 2: Externalizable Interface Implement serialization and deserialization for a class using the Externalizable interface. The class should be serialized in a custom format and deserialized back to its original state.
Solution:
import java.io.*;
class CustomObject implements Externalizable {
private int id; private String name; public CustomObject() { // Required default constructor for deserialization } public CustomObject(int id, String name) { this.id = id; this.name = name; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(id); out.writeObject(name); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { id = in.readInt(); name = (String) in.readObject(); } // Getters and setters
}
public class ExternalizableExample {
public static void main(String[] args) { CustomObject object = new CustomObject(1, "Object"); try (FileOutputStream fileOutputStream = new FileOutputStream("object.ser"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) { objectOutputStream.writeObject(object); System.out.println("Object serialized successfully."); } catch (IOException e) { e.printStackTrace(); } try (FileInputStream fileInputStream = new FileInputStream("object.ser"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) { CustomObject deserializedObject = (CustomObject) objectInputStream.readObject(); System.out.println("Object deserialized successfully."); System.out.println("ID: " + deserializedObject.getId()); System.out.println("Name: " + deserializedObject.getName()); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } }
}
Problem 3: Serialize and Deserialize a Binary Tree Implement functions to serialize and deserialize a binary tree.
Solution:
import java.util.*;
class TreeNode {
int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; }
}
public class BinaryTreeSerialization {
public static String serialize(TreeNode root) { if (root == null) return ""; StringBuilder sb = new StringBuilder(); serializeHelper(root, sb); return sb.toString(); } private static void serializeHelper(TreeNode node, StringBuilder sb) { if (node == null) { sb.append("null").append(","); return; } sb.append(node.val).append(","); serializeHelper(node.left, sb); serializeHelper(node.right, sb); } public static TreeNode deserialize(String data) { if (data == null || data.isEmpty()) return null; Queue<String> queue = new LinkedList<>(Arrays.asList(data.split(","))); return deserializeHelper(queue); } private static TreeNode deserializeHelper(Queue<String> queue) { String value = queue.poll(); if (value.equals("null")) return null; TreeNode node = new TreeNode(Integer.parseInt(value)); node.left = deserializeHelper(queue); node.right = deserializeHelper(queue); return node; } public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.right.left = new TreeNode(4); root.right.right = new TreeNode(5); String serializedTree = serialize(root); System.out.println("Serialized tree: " + serializedTree); TreeNode deserializedRoot = deserialize(serializedTree); System.out.println("Deserialized tree: " + (deserializedRoot != null)); }
}
((largestAndSmallest)) public static void largestAndSmallest(int[] numbers) {
int largest = Integer.MIN_VALUE; int smallest = Integer.MAX_VALUE; for (int number : numbers) { if (number > largest) { largest = number; } else if (number < smallest) { smallest = number; } }
Producer consumer :
import java.util.LinkedList;
public class Threadexample {
public static void main(String[] args) throws InterruptedException { // Object of a class that has both produce() // and consume() methods final PC pc = new PC(); // Create producer thread Thread t1 = new Thread(new Runnable() { @Override public void run() { try { pc.produce(); } catch (InterruptedException e) { e.printStackTrace(); } } }); // Create consumer thread Thread t2 = new Thread(new Runnable() { @Override public void run() { try { pc.consume(); } catch (InterruptedException e) { e.printStackTrace(); } } }); // Start both threads t1.start(); t2.start(); // t1 finishes before t2 t1.join(); t2.join(); } // This class has a list, producer (adds items to list // and consumber (removes items). public static class PC { // Create a list shared by producer and consumer // Size of list is 2. LinkedList<Integer> list = new LinkedList<>(); int capacity = 2; // Function called by producer thread public void produce() throws InterruptedException { int value = 0; while (true) { synchronized (this) { // producer thread waits while list // is full while (list.size() == capacity) wait(); System.out.println("Producer produced-" + value); // to insert the jobs in the list list.add(value++); // notifies the consumer thread that // now it can start consuming notify(); // makes the working of program easier // to understand Thread.sleep(1000); } } } // Function called by consumer thread public void consume() throws InterruptedException { while (true) { synchronized (this) { // consumer thread waits while list // is empty while (list.size() == 0) wait(); // to retrive the ifrst job in the list int val = list.removeFirst(); System.out.println("Consumer consumed-" + val); // Wake up producer thread notify(); // and sleep Thread.sleep(1000); } } } }
}
.
-
query to retrieve duplicate records from a table.
SELECT EmpID, EmpFname, Department COUNT(*) FROM EmployeeInfo GROUP BY EmpID, EmpFname, Department HAVING COUNT(*) > 1;
-
Write a query to retrieve the list of employees working in the same department.
Select DISTINCT E.EmpID, E.EmpFname, E.Department FROM EmployeeInfo E, Employee E1 WHERE E.Department = E1.Department AND E.EmpID != E1.EmpID;
Q24. Write a query to retrieve the last 3 records from the EmployeeInfo table.
SELECT * FROM EmployeeInfo WHERE EmpID <=3 UNION SELECT * FROM (SELECT * FROM EmployeeInfo E ORDER BY E.EmpID DESC) AS E1 WHERE E1.EmpID <=3;
Q25. Write a query to find the third-highest salary from the EmpPosition table.
SELECT TOP 1 salary FROM( SELECT TOP 3 salary FROM employee_table ORDER BY salary DESC) AS emp ORDER BY salary ASC;
-
How to write a query to show the details of a student from Students table whose FirstName starts with ‘K’?
SELECT * FROM Students WHERE FirstName LIKE ‘K%’.
How to display employee records who gets more salary than the average salary in the department? This can be done by this query –
1 Select * from employee where salary>(select avg(salary) from dept, employee where dept.deptno = employee.deptno;
Employee( empid, salary, departId,) Department(departId, deparment name )