Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

Implement Binary Search in Java using recursion.

Answer»

public class Main{ //Recursive method for binary search private static boolean binarySearch(int[] arr, int low, int high, int KEY){ //Calculating Mid. int mid = (low + high)/2; //Base Case. if(low > high) return false; //Checking if the key is found in the middle. if(arr[mid] == key) return true; //Searching on the left half if a key exists there. if(key < arr[mid]) return binarySearch(arr, low, mid-1, key); //Searching on the other half OTHERWISE. return binarySearch(arr, mid+1, high, key); }public static void main(String[] args) { int[] arr = {2, 5, 9, 13, 17, 21, 30}; if(binarySearch(arr, 0, (arr.length-1), 30)) System.out.println(" Element Found. "); else System.out.println(" Element not Found.");}}

In the above CODE, we are finding the middle element each TIME and checking if the element is in the middle or not. If it is not, then we check on which side from the middle it exists. And Recursively searching on the particular subarray. So this way we are reducing the search space by 2 every time. So the search time is very low.

2.

Write a Java program for solving the Tower of Hanoi Problem.

Answer»

public CLASS InterviewBit{ //Recursive Method for SOLVING the Tower of hanoi. private static void TOH(CHAR source, char auxiliary, char destination, int numOfDisk){ if (numOfDisk > 0){ TOH(source, destination, auxiliary, numOfDisk-1); System.out.println("Move 1 disk from "+source+" to "+destination+" using "+auxiliary+"."); TOH(auxiliary, source, destination, numOfDisk-1); } } public static void main(String[] args) { TOH('A','B','C', 3); }}

In the above code we are first moving the n-1 disk from Tower A to Tower B, then moving that nth disk from Tower A to Tower C, and finally, the remaining n-1 disk from Tower B to Tower C. And we are doing this recursively for the n-1 disk.

3.

Write a java program to check if any number given as input is the sum of 2 prime numbers.

Answer»

Example :

Input - 18

Output - 

18 = 13 + 5
18 = 11 + 7

public class InterviewBit{ // Method to Check Prime Number private static int check_prime(int num){ int flag = 0; for(int i = 2; i<=num/2; i++){ if(num%i == 0){ flag = 1; return 1; } } if(flag == 0) return 0; return 1; } // Method to get print the prime sum private static void find(int num){ for(int i = 2; i <= num/2; i++){ if(check_prime(i) == 0){ if(check_prime(num-i) == 0) System.out.println(num + " = "+ (num-i) + " "+ i); } } } public static void MAIN(String[] args) { find(18); }}

In the above CODE, for any number N, we find all the 2 pairs of numbers that are added together resulting in n. And each checking number if it is prime. If it is prime then we are printing that.

4.

Write a Java program to rotate arrays 90 degree clockwise by taking matrices from user input.

Answer»

mport java.util.Scanner;public class InterviewBit{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int no; System.out.print("Enter size of Array : "); no = sc.nextInt(); int[][] a = new int[no][no]; System.out.print("Enter "+ no*no+" Element Array : "); for(int i = 0; i<no; i++){ for(int j = 0; j<no; j++){ a[i][j] = sc.nextInt(); } } System.out.print("\nArray Before Rotation\N\n"); for(int i = 0; i<no; i++){ for(int j = 0; j<no; j++){ System.out.print(a[i][j] + " "); } System.out.println(); } System.out.println("\n"); //Rotation //Transpose for(int i = 0; i < no; i++){ for(int j = i; j < no; j++){ int temp = a[i][j]; a[i][j] = a[j][i]; a[j][i] = temp; } } //Reverse Each row for(int i = 0; i < no; i++){ int l, j; for(j = 0, l = no -1; j < l; j++){ int temp = a[i][j]; a[i][j] = a[i][l]; a[i][l] = temp; l--; } } System.out.println("Array After Rotation - \n"); for(int i = 0; i<no; i++){ for(int j = 0; j<no; j++){ System.out.print(a[i][j] + " "); } System.out.println(); } }}

In the above code, for rotating the MATRIX to  90 degrees we are first TRANSPOSING the matrix so the row BECOMES the column. And after that, we are reversing each row in the matrix. So this is how the matrix GOT rotated.

5.

Write a Java program to reverse a string.

Answer» CLASS InterviewBit{ PUBLIC static void main(String[] ARGS){ //Input String String STR = "Welcome to InterviewBit"; //Pointers. int i = 0, j = str.length()-1; //Result character array to store the reversed string. char[] revString = new char[j+1]; //Looping and reversing the string. while(i < j){ revString[j] = str.charAt(i); revString[i] = str.charAt(j); i++; j--; } //Printing the reversed String. System.out.println("Reversed String = " + String.valueOf(revString)); }}

In the above code, we are storing the last character from the string to the first and the first value to the last in the output character array. And doing the same THING in the loop for the remaining 2nd to n-1 characters. This is how the string will be reversed.

6.

Write a Java program to create and throw custom exceptions.

Answer»

class InterviewBit { public static void main(String args[]) throws CustomException { // Throwing the custom EXCEPTION be passing the message throw new CustomException(" This is my custom Exception "); }}//Creating Custom Exception Classclass CustomException extends Exception{ //Defining Constructor to throw exception message public CustomException(String message){ super(message); }}

We have created the exception class named with CustomException and called the BASE exception constructor with the ERROR message that we want to print. And to avoid HANDLING exceptions in the main method, we have used the throws keyword in the method declaration.

7.

Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing sum of digits in each step and inturn doing sum of digits of that sum, the ultimate result (when there is only one digit left) is 1.

Answer»

Example, CONSIDER the number:

  • STEP 1: 163 => 1+6+3 = 10
  • Step 2: 10 => 1+0 = 1 => Hence 163 is a magic number
public CLASS IBMagicNumber{ public static void main(String[] args) { INT num = 163; int sumOfDigits = 0; while (num > 0 || sumOfDigits > 9) { if (num == 0) { num = sumOfDigits; sumOfDigits = 0; } sumOfDigits += num % 10; num /= 10; } // If SUM is 1, original number is magic number if(sumOfDigits == 1) { System.out.println("Magic number"); }else { System.out.println("Not magic number"); } }}
8.

Given an array of non-duplicating numbers from 1 to n where one number is missing, write an efficient java program to find that missing number.

Answer»

Idea is to find the sum of n natural numbers using the formula and then finding the sum of numbers in the given array. Subtracting these two SUMS results in the number that is the actual missing number. This results in O(n) TIME complexity and O(1) space complexity.

public class IBMissingNumberProblem { public static void main(String[] args) { INT[] array={4,3,8,7,5,2,6}; int missingNumber = findMissingNum(array); System.out.println("Missing Number is "+ missingNumber); } public static int findMissingNum(int[] array) { int n=array.length+1; int sumOfFirstNNums=n*(n+1)/2; int actualSumOfArr=0; for (int i = 0; i &LT; array.length; i++) { actualSumOfArr+=array[i]; } return sumOfFirstNNums-actualSumOfArr; }}
9.

Write a Java Program to find the factorial of a given number.

Answer»

public CLASS FindFactorial { public static VOID main(String[] args) { int num = 10; LONG factorialResult = 1l; for(int i = 1; i <= num; ++i) { factorialResult *= i; } System.out.println("Factorial: "+factorialResult); }}

10.

Write a Java program to check if the two strings are anagrams.

Answer»

The MAIN idea is to validate the length of strings and then if found EQUAL, convert the STRING to char array and then sort the arrays and CHECK if both are equal.

import java.util.Arrays;import java.util.Scanner;public class InterviewBit { public static void main(String[] args) { Scanner s = new Scanner(System.in); //Input from TWO strings System.out.print("First String: "); String string1 = s.nextLine(); System.out.print("Second String: "); String string2 = s.nextLine(); // check for the length if(string1.length() == string2.length()) { // convert strings to char array char[] characterArray1 = string1.toCharArray(); char[] characterArray2 = string2.toCharArray(); // sort the arrays Arrays.sort(characterArray1); Arrays.sort(characterArray2); // check for equality, if found equal then anagram, else not an anagram boolean isAnagram = Arrays.equals(characterArray1, characterArray2); System.out.println("Anagram: "+ isAnagram); }}
11.

Write a Java Program to print Fibonacci Series using Recursion.

Answer»

class InterviewBit { public static void printFibonacci(int val_1, int val_2, int num){ //Base Case if(num == 0) return; //Printing the next Fibonacci number System.out.PRINT( val_1 + val_2 + " "); //Recursively calling for printing Fibonacci for remaining length printFibonacci(val_2, val_1+val_2, --num); } public static void main(String args[]) { System.out.println(" *** Fibonacci Series *** "); //Printing the FIRST two values System.out.print("0 1 "); //Calling Method to print the fibonacci for length 10 printFibonacci(0, 1, 10); }}

In the above code, we are printing the base 2 Fibonacci values 0 and 1. And then based on the length of Fibonacci to be printed, we are using the helper FUNCTION to print that.

12.

Check if a given string is palindrome using recursion.

Answer»

/** Java program to CHECK if a given inputted string is palindrome or not using recursion.*/import java.util.*;public class InterviewBit { public static void main(String args[]) { Scanner s = new Scanner(System.in); String WORD = s.nextLine(); System.out.println("Is "+word+" palindrome? - "+isWordPalindrome(word)); } public static BOOLEAN isWordPalindrome(String word){ String reverseWord = getReverseWord(word); //if word equals its reverse, then it is a palindrome if(word.equals(reverseWord)){ return true; } return false; } public static String getReverseWord(String word){ if(word == NULL || word.isEmpty()){ return word; } return word.charAt(word.length()- 1) + getReverseWord(word.substring(0, word.length() - 1)); } }