0% found this document useful (0 votes)
8 views

Deloitte_Coding

The document contains a series of coding questions and solutions, primarily focused on Java programming concepts such as recursion, data structures, algorithms, and string manipulation. It includes examples of code implementations for various problems, including finding factorials, reversing linked lists, and performing matrix rotations. Additionally, it covers theoretical questions regarding abstract classes, interfaces, and method overloading versus overriding.
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)
8 views

Deloitte_Coding

The document contains a series of coding questions and solutions, primarily focused on Java programming concepts such as recursion, data structures, algorithms, and string manipulation. It includes examples of code implementations for various problems, including finding factorials, reversing linked lists, and performing matrix rotations. Additionally, it covers theoretical questions regarding abstract classes, interfaces, and method overloading versus overriding.
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/ 20

ItsRunTym

Coding Ques with Solutions

1. What is System.out.println()?
2. What is the difference between Abstract class, and Interface? Can we create a constructor
of both?
3. Can we have different written types in method overloading and overriding?
4. Implement a program to find the factorial of a number using recursion.
5. Write code to reverse a linked list.
6. Solve a mathematical or logical aptitude question involving patterns or series.
7. Design an algorithm to solve a problem related to data structures, such as sorting or
searching.
8. Write a program that takes an octal number as input and converts it to binary.
9. Write a program to identify the node at which two linked lists merge.
10. Create a program that swaps two given numbers without using an extra variable.
11. Write a program to rotate a matrix by 90 degrees in the clockwise direction.
12. Implement Kadane’s Algorithm to determine the maximum sum of a contiguous subarray.
13. Write a program to verify if two given strings are anagrams.
14. Given an array with numbers from 1 to n, find the missing number.
15. Write a program to find the longest substring in a string that is a palindrome.
16. Rotate an array by k positions.
17. Write a program to find the spiral traversal of a matrix.
18. Solve a problem involving string manipulation or pattern matching.
19. Implement a binary search algorithm in Java and discuss its time complexity.
20. Explain the concept of dynamic programming and provide an example problem.
21. Solve a problem involving tree traversal or manipulation, such as finding the lowest
common ancestor.
22. Design a class hierarchy for a banking system encompassing accounts, transactions, and
customers.
1. What is System.out.println()?

System.out.println() is a method in Java used to print output to the console. The System class is part
of the java.lang package, and out is a static instance of PrintStream. The println() method prints the
message followed by a new line.

2. Difference between Abstract class and Interface? Can we create a constructor for both?

• Abstract Class: Can have both abstract (without implementation) and concrete methods
(with implementation). A class can inherit from only one abstract class due to single
inheritance in Java.

• Interface: Only contains abstract methods (until Java 8, after which default methods with
implementation were introduced). A class can implement multiple interfaces due to multiple
inheritance.

Constructors:

• Abstract class: Can have constructors, which are invoked when the class is subclassed.

• Interface: Cannot have constructors.

3. Can we have different return types in method overloading and overriding?

• Overloading: Yes, method overloading can have different return types.

• Overriding: No, the return type must be the same or co-variant (in case of inheritance).

4. Program to find the factorial of a number using recursion

java

public class Factorial {

public static int factorial(int n) {

if (n == 0) return 1;

return n * factorial(n - 1);

public static void main(String[] args) {

int num = 5;

System.out.println("Factorial of " + num + " is: " + factorial(num));

}
5. Write code to reverse a linked list

java

class LinkedList {

Node head;

class Node {

int data;

Node next;

Node(int d) {

data = d;

next = null;

public void push(int newData) {

Node newNode = new Node(newData);

newNode.next = head;

head = newNode;

public void reverse() {

Node prev = null, current = head, next = null;

while (current != null) {

next = current.next;

current.next = prev;

prev = current;

current = next;

}
head = prev;

public void printList() {

Node temp = head;

while (temp != null) {

System.out.print(temp.data + " ");

temp = temp.next;

public static void main(String[] args) {

LinkedList list = new LinkedList();

list.push(20);

list.push(15);

list.push(10);

list.push(5);

System.out.println("Original Linked List:");

list.printList();

list.reverse();

System.out.println("\nReversed Linked List:");

list.printList();

6. Solve a mathematical or logical aptitude question involving patterns or series

Example question: Find the next number in the series 1, 4, 9, 16, ? The numbers are squares of
natural numbers. The next number is 25.

java
public class PatternSeries {

public static void main(String[] args) {

int[] series = {1, 4, 9, 16};

int next = (int)Math.pow(Math.sqrt(series[series.length - 1]) + 1, 2);

System.out.println("Next number in series: " + next);

7. Design an algorithm to solve a problem related to data structures, such as sorting or searching

Example: Sorting an array using Bubble Sort.

java

public class BubbleSort {

public static void bubbleSort(int[] arr) {

int n = arr.length;

for (int i = 0; i < n-1; i++) {

for (int j = 0; j < n-i-1; j++) {

if (arr[j] > arr[j+1]) {

// Swap arr[j+1] and arr[j]

int temp = arr[j];

arr[j] = arr[j+1];

arr[j+1] = temp;

public static void main(String[] args) {

int[] arr = {64, 34, 25, 12, 22, 11, 90};

bubbleSort(arr);
System.out.println("Sorted array:");

for (int i = 0; i < arr.length; i++) {

System.out.print(arr[i] + " ");

8. Write a program that takes an octal number as input and converts it to binary

java

import java.util.Scanner;

public class OctalToBinary {

public static String octalToBinary(int octal) {

int decimal = 0, i = 0;

while (octal != 0) {

decimal += (octal % 10) * Math.pow(8, i);

++i;

octal /= 10;

return Integer.toBinaryString(decimal);

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter octal number: ");

int octal = sc.nextInt();

System.out.println("Binary equivalent: " + octalToBinary(octal));

}
9. Write a program to identify the node at which two linked lists merge

java

class LinkedList {

Node head;

class Node {

int data;

Node next;

Node(int d) { data = d; next = null; }

public Node findIntersection(LinkedList list1, LinkedList list2) {

int length1 = getLength(list1.head);

int length2 = getLength(list2.head);

Node ptr1 = list1.head;

Node ptr2 = list2.head;

// Move the pointer of the longer list to the same starting point

if (length1 > length2) {

for (int i = 0; i < length1 - length2; i++) ptr1 = ptr1.next;

} else {

for (int i = 0; i < length2 - length1; i++) ptr2 = ptr2.next;

// Traverse both lists and find the intersection

while (ptr1 != null && ptr2 != null) {

if (ptr1 == ptr2) return ptr1;

ptr1 = ptr1.next;

ptr2 = ptr2.next;
}

return null; // No intersection

private int getLength(Node head) {

int length = 0;

while (head != null) {

length++;

head = head.next;

return length;

public static void main(String[] args) {

LinkedList list1 = new LinkedList();

LinkedList list2 = new LinkedList();

// Add nodes to list1 and list2 and create intersection

// Call findIntersection() to test

10. Create a program that swaps two given numbers without using an extra variable

java

public class SwapNumbers {

public static void swap(int a, int b) {

a = a + b;

b = a - b;

a = a - b;

System.out.println("After swapping: a = " + a + ", b = " + b);


}

public static void main(String[] args) {

int a = 10, b = 20;

System.out.println("Before swapping: a = " + a + ", b = " + b);

swap(a, b);

11. Write a program to rotate a matrix by 90 degrees in the clockwise direction

java

public class RotateMatrix {

public static void rotateMatrix(int[][] matrix) {

int n = matrix.length;

for (int i = 0; i < n / 2; i++) {

for (int j = i; j < n - i - 1; j++) {

int temp = matrix[i][j];

matrix[i][j] = matrix[n - j - 1][i];

matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];

matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];

matrix[j][n - i - 1] = temp;

public static void main(String[] args) {

int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

rotateMatrix(matrix);

for (int i = 0; i < matrix.length; i++) {

for (int j = 0; j < matrix[i].length; j++) {


System.out.print(matrix[i][j] + " ");

System.out.println();

12. Implement Kadane’s Algorithm to determine the maximum sum of a contiguous subarray

java

public class KadaneAlgorithm {

public static int maxSubArraySum(int[] arr) {

int maxSoFar = arr[0];

int maxEndingHere = arr[0];

for (int i = 1; i < arr.length; i++) {

maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);

maxSoFar = Math.max(maxSoFar, maxEndingHere);

return maxSoFar;

public static void main(String[] args) {

int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};

System.out.println("Maximum subarray sum: " + maxSubArraySum(arr));

13. Write a program to verify if two given strings are anagrams

java
import java.util.Arrays;

public class AnagramCheck {

public static boolean areAnagrams(String str1, String str2) {

if (str1.length() != str2.length()) {

return false;

char[] arr1 = str1.toCharArray();

char[] arr2 = str2.toCharArray();

Arrays.sort(arr1);

Arrays.sort(arr2);

return Arrays.equals(arr1, arr2);

public static void main(String[] args) {

String str1 = "listen";

String str2 = "silent";

System.out.println("Are they anagrams? " + areAnagrams(str1, str2));

14. Given an array with numbers from 1 to n, find the missing number

java

public class MissingNumber {

public static int findMissingNumber(int[] arr, int n) {

int totalSum = (n * (n + 1)) / 2;

int arrSum = 0;
for (int num : arr) {

arrSum += num;

return totalSum - arrSum;

public static void main(String[] args) {

int[] arr = {1, 2, 4, 5, 6};

int n = 6;

System.out.println("Missing number: " + findMissingNumber(arr, n));

15. Write a program to find the longest substring in a string that is a palindrome

java

public class LongestPalindromeSubstring {

public static String longestPalindrome(String s) {

if (s == null || s.length() < 1) return "";

int start = 0, end = 0;

for (int i = 0; i < s.length(); i++) {

int len1 = expandAroundCenter(s, i, i);

int len2 = expandAroundCenter(s, i, i + 1);

int len = Math.max(len1, len2);

if (len > end - start) {

start = i - (len - 1) / 2;

end = i + len / 2;
}

return s.substring(start, end + 1);

private static int expandAroundCenter(String s, int left, int right) {

int l = left, r = right;

while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {

l--;

r++;

return r - l - 1;

public static void main(String[] args) {

String s = "babad";

System.out.println("Longest Palindromic Substring: " + longestPalindrome(s));

16. Rotate an array by k positions

java

public class RotateArray {

public static void rotate(int[] arr, int k) {

int n = arr.length;

k = k % n; // Handle cases where k > n

reverse(arr, 0, n - 1);

reverse(arr, 0, k - 1);
reverse(arr, k, n - 1);

public static void reverse(int[] arr, int start, int end) {

while (start < end) {

int temp = arr[start];

arr[start] = arr[end];

arr[end] = temp;

start++;

end--;

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5, 6, 7};

int k = 3;

rotate(arr, k);

System.out.print("Rotated array: ");

for (int num : arr) {

System.out.print(num + " ");

17. Write a program to find the spiral traversal of a matrix

java

public class SpiralTraversal {

public static void printSpiral(int[][] matrix) {

int rowStart = 0, rowEnd = matrix.length - 1;


int colStart = 0, colEnd = matrix[0].length - 1;

while (rowStart <= rowEnd && colStart <= colEnd) {

for (int i = colStart; i <= colEnd; i++) {

System.out.print(matrix[rowStart][i] + " ");

rowStart++;

for (int i = rowStart; i <= rowEnd; i++) {

System.out.print(matrix[i][colEnd] + " ");

colEnd--;

if (rowStart <= rowEnd) {

for (int i = colEnd; i >= colStart; i--) {

System.out.print(matrix[rowEnd][i] + " ");

rowEnd--;

if (colStart <= colEnd) {

for (int i = rowEnd; i >= rowStart; i--) {

System.out.print(matrix[i][colStart] + " ");

colStart++;

public static void main(String[] args) {

int[][] matrix = {
{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

System.out.print("Spiral Traversal: ");

printSpiral(matrix);

18. Solve a problem involving tree traversal or manipulation, such as finding the lowest common
ancestor.

Solution in Java:

java

class TreeNode {

int val;

TreeNode left, right;

TreeNode(int val) { this.val = val; }

public class LowestCommonAncestor {

public static TreeNode findLCA(TreeNode root, TreeNode p, TreeNode q) {

if (root == null || root == p || root == q) return root;

TreeNode left = findLCA(root.left, p, q);

TreeNode right = findLCA(root.right, p, q);

return (left != null && right != null) ? root : (left != null ? left : right);

public static void main(String[] args) {

TreeNode root = new TreeNode(3);

root.left = new TreeNode(5);

root.right = new TreeNode(1);


System.out.println(findLCA(root, root.left, root.right).val); // Output: 3

19. Implement a binary search algorithm in Java and discuss its time complexity.

Solution:

java

public class BinarySearch {

public static int binarySearch(int[] arr, int target) {

int left = 0, right = arr.length - 1;

while (left <= right) {

int mid = left + (right - left) / 2;

if (arr[mid] == target) return mid;

if (arr[mid] < target) left = mid + 1;

else right = mid - 1;

return -1; // Target not found

public static void main(String[] args) {

int[] arr = {1, 3, 5, 7, 9};

System.out.println(binarySearch(arr, 5)); // Output: 2

Time Complexity: O(log n).

20. Explain the concept of dynamic programming and provide an example problem.

Dynamic programming (DP) solves problems by breaking them into smaller subproblems and storing
solutions to avoid redundant calculations.

Example Problem: Fibonacci sequence.


Solution in Java:

java

public class FibonacciDP {


public static int fibonacci(int n) {

int[] dp = new int[n + 1];

dp[0] = 0; dp[1] = 1;

for (int i = 2; i <= n; i++) {

dp[i] = dp[i - 1] + dp[i - 2];

return dp[n];

public static void main(String[] args) {

System.out.println(fibonacci(10)); // Output: 55

21. Solve a problem involving string manipulation or pattern matching.

Example Problem: Check if two strings are anagrams.


Solution in Java:

java

import java.util.Arrays;

public class AnagramCheck {

public static boolean areAnagrams(String str1, String str2) {

if (str1.length() != str2.length()) return false;

char[] arr1 = str1.toCharArray();

char[] arr2 = str2.toCharArray();

Arrays.sort(arr1);

Arrays.sort(arr2);

return Arrays.equals(arr1, arr2);

public static void main(String[] args) {

System.out.println(areAnagrams("listen", "silent")); // true


}

22. Design a class hierarchy for a banking system encompassing accounts, transactions, and
customers.

Example Code in Java:

java

class Customer {

private String name;

private String customerId;

// Constructor, getters, setters

abstract class Account {

protected String accountNumber;

protected double balance;

public abstract void deposit(double amount);

public abstract void withdraw(double amount);

class SavingsAccount extends Account {

private double interestRate;

@Override

public void deposit(double amount) { balance += amount; }

@Override

public void withdraw(double amount) { if (balance >= amount) balance -= amount; }

class Transaction {

private String transactionId;

private String accountId;

private double amount;


private String type; // Deposit or Withdrawal

// Constructor, getters, setters

You might also like