[Go to site: main page, start]

0% found this document useful (0 votes)
5 views3 pages

Top Java Coding Questions for Interviews

Uploaded by

ilakkya005
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)
5 views3 pages

Top Java Coding Questions for Interviews

Uploaded by

ilakkya005
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

Top 10 Java Coding Questions for Placements

■ Palindrome Check (String)


public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
String rev = new StringBuilder(str).reverse().toString();
if([Link](rev))
[Link](str + " is Palindrome");
else
[Link](str + " is Not Palindrome");
}
}
Checks if a string reads the same forward and backward. Time: O(n), Space: O(n).

■ Fibonacci Series
public class Fibonacci {
public static void main(String[] args) {
int n = 10, first = 0, second = 1;
[Link]("Fibonacci: ");
for (int i = 0; i < n; i++) {
[Link](first + " ");
int next = first + second;
first = second;
second = next;
}
}
}
Prints first n Fibonacci numbers. Time: O(n), Space: O(1).

■ Factorial (Recursion)
public class Factorial {
static int fact(int n) {
if (n == 0 || n == 1) return 1;
return n * fact(n - 1);
}
public static void main(String[] args) {
int num = 5;
[Link]("Factorial of " + num + " = " + fact(num));
}
}
Recursively calculates factorial. Time: O(n), Space: O(n) recursion depth.

■ Prime Number Check


public class PrimeCheck {
public static void main(String[] args) {
int num = 29;
boolean isPrime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
[Link](num + (isPrime ? " is Prime" : " is Not Prime"));
}
}
Checks if number is prime. Time: O(n), can be optimized to O(√n).
■ Reverse a Number
public class ReverseNumber {
public static void main(String[] args) {
int num = 1234, rev = 0;
while (num != 0) {
int digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
[Link]("Reversed Number = " + rev);
}
}
Reverses digits of a number. Time: O(d) where d = digits, Space: O(1).

■ Armstrong Number
public class Armstrong {
public static void main(String[] args) {
int num = 153, sum = 0, temp = num;
while (temp != 0) {
int digit = temp % 10;
sum += [Link](digit, 3);
temp /= 10;
}
[Link](num + (sum == num ? " is Armstrong" : " is Not Armstrong"));
}
}
Checks if number = sum of cubes of digits. Time: O(d), Space: O(1).

■ Largest & Smallest in Array


public class ArrayMinMax {
public static void main(String[] args) {
int arr[] = {3, 5, 7, 2, 8};
int min = arr[0], max = arr[0];
for (int n : arr) {
if (n < min) min = n;
if (n > max) max = n;
}
[Link]("Min = " + min + ", Max = " + max);
}
}
Finds min and max element in array. Time: O(n), Space: O(1).

■ Anagram Check
import [Link];
public class Anagram {
public static void main(String[] args) {
String s1 = "listen", s2 = "silent";
char[] a = [Link]();
char[] b = [Link]();
[Link](a);
[Link](b);
if ([Link](a, b))
[Link]("Anagram");
else
[Link]("Not Anagram");
}
}
Two strings are anagrams if sorted characters match. Time: O(n log n).

■ Pattern Printing (Star Triangle)


public class Pattern {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++)
[Link]("* ");
[Link]();
}
}
}
Prints right-angle triangle. Time: O(n²), Space: O(1).

■ Binary Search
public class BinarySearch {
static int search(int arr[], int target) {
int left = 0, right = [Link] - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
public static void main(String[] args) {
int arr[] = {2, 4, 6, 8, 10, 12};
int target = 8;
int index = search(arr, target);
[Link]("Element found at index: " + index);
}
}
Performs binary search on sorted array. Time: O(log n), Space: O(1).

Common questions

Powered by AI

The palindrome check for a string has a time complexity of O(n) where n is the length of the string because it involves reversing the string and comparing it to the original . Checking whether a number is an Armstrong number also has a time complexity of O(d), where d is the number of digits in the number, as it involves checking the sum of the cubes of its digits . In terms of computational efficiency, if the word length and the number of digits are comparable, both operations would essentially perform similarly with linear complexity based on their respective 'n' and 'd' parameters. Therefore, the overall computational efficiency will depend on the specific lengths and size of the string and the number.

Reversing a number operates with a space complexity of O(1) as it involves manipulation of integer variables without storing additional copies of the entire number . Reversing a string, however, involves creating a new string to store the reversed characters, resulting in O(n) space complexity where n is the length of the string . This disparity means reversing strings requires linear space proportional to the input size, which is a consideration for applications with large strings.

Binary search has a time complexity of O(log n), but it requires the input array to be sorted . Applying binary search to an unsorted array would not yield correct results, as the assumptions of order that binary search depends on do not hold. Thus, before using binary search on an unsorted array, it has to be sorted, which would take O(n log n) time. Therefore, using binary search directly on an unsorted array offers no practical advantage without prior sorting, which negates the fast O(log n) search time, making the approach inefficient in terms of overall time complexity.

The calculation of Armstrong numbers involves cubing each digit and summing these cubes, which can lead to integer overflow for numbers with many digits, especially as the number of digits increases beyond typical integer limits . This results in inaccurate calculations or errors when the resulting sum exceeds the maximum value that can be held by standard integer types, such as int in Java. Using larger data types like long or even BigInteger might be necessary to handle very large numbers without overflow.

A recursive method for calculating factorial is less optimal in terms of space complexity compared to an iterative approach. Recursive methods have a space complexity of O(n) due to the call stack depth required for recursion . This can lead to stack overflow errors for large values of 'n'. Iterative approaches, on the other hand, have a space complexity of O(1) as they only use a fixed number of additional variables regardless of the size of 'n'. Therefore, for larger input sizes, an iterative solution is preferable as it is less likely to encounter limitations of stack space.

Finding the largest and smallest elements in an array has a time complexity of O(n) as each element needs to be checked . Parallelizing the process could potentially improve performance by dividing the array into segments and finding local maxima and minima in parallel threads, which would then be compared to find the global max and min. However, the overhead of creating threads and handling synchronization may offset the benefits depending on the size of the array and the computational resources available. Careful consideration is needed to determine whether the parallelization outweighs its overhead for a given use case.

Detecting anagrams by sorting the strings and comparing them has a time complexity of O(n log n) due to the sorting operation . The strength of this method lies in its simplicity and readability, providing a clear way to compare the character composition of two strings. However, it is not optimal for very large strings or mass anagram checks where a hash map implementation might be more efficient, offering a linear time complexity O(n) by counting character occurrences. Sorting also uses additional space for sorting operations, which could be a downside in memory-constrained environments.

The prime-checking algorithm iterates from 2 to num/2, checking divisibility to determine primality, resulting in O(n) complexity . To optimize this to O(√n), the loop can be reduced to iterate only from 2 to √n because if 'n' is divisible by any number greater than its square root, it must also be divisible by a smaller corresponding factor. This reduces unnecessary checks and significantly enhances performance, especially for large numbers.

Pattern printing of a star triangle has a time complexity of O(n²) because it involves two nested loops iterating over the number of rows . While this is generally efficient for small or moderate sizes, for much larger sizes, the runtime can become significant. To optimize, one could precompute the star pattern for a maximum expected size and store it, allowing quick retrieval for repeated use or lookups, hence reducing actual generation time to O(1) time for each print after setup, trading space complexity for time.

Iterative calculation of the Fibonacci series is computed in O(n) time with O(1) space, making it efficient for both computation and memory . Recursively calculating Fibonacci, however, has an exponential time complexity of O(2^n) due to repeated calculations of the same subproblems without memoization, making it vastly inefficient for large 'n'. The recursive approach is more intuitive and straightforward in its definition but is only feasible with small 'n' values or where clarity takes precedence over performance.

You might also like