0% found this document useful (0 votes)
3 views13 pages

Java Interview Prep

The document is a comprehensive Java interview problem bank covering various topics such as number-based problems, loops, patterns, arrays, strings, recursion, and logic building. It includes optimized solutions, logic explanations, and interview tips for each problem, providing essential coding techniques and best practices. The content is tailored for students at Adhi College of Engineering & Technology, specifically for interview preparation.

Uploaded by

sudharsanrj1971
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)
3 views13 pages

Java Interview Prep

The document is a comprehensive Java interview problem bank covering various topics such as number-based problems, loops, patterns, arrays, strings, recursion, and logic building. It includes optimized solutions, logic explanations, and interview tips for each problem, providing essential coding techniques and best practices. The content is tailored for students at Adhi College of Engineering & Technology, specifically for interview preparation.

Uploaded by

sudharsanrj1971
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

Java Interview

Complete Problem Bank


Numbers • Patterns • Arrays • Strings • Recursion • Logic

Optimised Solutions + Logic Explanation + Interview Tips

Prepared for: Bubu | Adhi College of Engineering & Technology


1. Number-Based Problems
■ Prime Number Check
Logic:
• Divisibility only needs checking up to √n (not n-1).

• Skip even numbers after checking 2.

• Time: O(√n) | Space: O(1)

Code:
static boolean isPrime(int n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 3; i * i <= n; i += 2)
if (n % i == 0) return false;
return true;
}

■ Interview Tip: Interviewers love the i*i<=n trick — say it aloud.

■ Palindrome Number (e.g. 121)


Logic:
• Reverse only the second half of the number.

• If reversed half == first half → palindrome.

• Handles negatives and trailing-zero edge cases.

Code:
static boolean isPalindrome(int n) {
if (n < 0 || (n % 10 == 0 && n != 0)) return false;
int rev = 0;
while (n > rev) {
rev = rev * 10 + n % 10;
n /= 10;
}
return n == rev || n == rev / 10;
}

■ Interview Tip: Half-reversal is O(log n) digits — much cleaner than full reverse.
■ Armstrong Number (e.g. 153 = 1³+5³+3³)
Logic:
• Count digits first, then raise each digit to that power.

• 153 has 3 digits → 1³+5³+3³ = 153 ✓

Code:
static boolean isArmstrong(int n) {
int digits = [Link](n).length();
int sum = 0, tmp = n;
while (tmp > 0) {
int d = tmp % 10;
sum += (int) [Link](d, digits);
tmp /= 10;
}
return sum == n;
}

■ Interview Tip: Always mention you're using digit-count, not hardcoded 3.

■ Reverse a Number
Logic:
• Extract last digit with n%10, build reversed number.

• Divide n by 10 each iteration until n==0.

Code:
static int reverseNum(int n) {
int rev = 0;
while (n != 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
return rev;
}

■ Interview Tip: Mention overflow handling for int if interviewer probes.


■ Count Digits & Sum of Digits
Logic:
• Count: log10(n)+1 gives digit count in O(1).

• Sum: keep extracting n%10 and accumulate.

Code:
static int countDigits(int n) {
return (n == 0) ? 1 : (int)(Math.log10([Link](n))) + 1;
}
static int sumDigits(int n) {
int s = 0;
while (n != 0) { s += n % 10; n /= 10; }
return s;
}

■ Interview Tip: The log10 trick for count = instant brownie points.

■ GCD / HCF (Euclidean) & LCM


Logic:
• GCD: gcd(a,b) = gcd(b, a%b) — recurse until b==0.

• LCM: lcm(a,b) = (a/gcd(a,b)) * b (divide first to avoid overflow).

• Time: O(log min(a,b)).

Code:
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}

■ Interview Tip: Always divide before multiply in LCM to prevent int overflow.

2. Loop & Pattern Problems


■ Right-Angle Triangle (stars)
Logic:
• Outer loop i=1..n → rows. Inner loop j=1..i → print '*'.

Code:
// n=4 output:
// *
// **
// ***
// ****
for (int i=1;i<=n;i++){
for(int j=1;j<=i;j++) [Link]('*');
[Link]();
}
■ Pyramid (centred star)
Logic:
• Spaces = n-i, Stars = 2*i-1 for row i.

Code:
for(int i=1;i<=n;i++){
for(int j=i;j<n;j++) [Link](' ');
for(int j=1;j<=2*i-1;j++) [Link]('*');
[Link]();
}

■ Interview Tip: Explain space formula: n-i keeps the peak centred.

■ Diamond Pattern
Logic:
• Upper half = pyramid (i: 1→n).

• Lower half = inverted pyramid (i: n-1→1).

Code:
for(int i=1;i<=n;i++){
for(int j=i;j<n;j++) [Link](' ');
for(int j=1;j<=2*i-1;j++) [Link]('*');
[Link]();
}
for(int i=n-1;i>=1;i--){
for(int j=n;j>i;j--) [Link](' ');
for(int j=1;j<=2*i-1;j++) [Link]('*');
[Link]();
}

■ Interview Tip: Two loops, same logic — shows clean loop control.

■ Number Pattern 1 / 12 / 123 …


Logic:
• Outer loop i=1..n (row), inner loop j=1..i (print j).

Code:
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++) [Link](j);
[Link]();
}

3. Array Basics
■ Find Max & Min
Logic:
• Single pass, O(n) time, O(1) space.

• Initialise both with arr[0].

Code:
static int[] maxMin(int[] a) {
int max=a[0], min=a[0];
for(int x:a){ max=[Link](max,x); min=[Link](min,x); }
return new int[]{max,min};
}

■ Interview Tip: One pass beats two separate loops — mention it.

■ Second Largest Element


Logic:
• Track first and second max in one pass.

• Update second whenever a new first is found.

Code:
static int secondLargest(int[] a) {
int first=Integer.MIN_VALUE, second=Integer.MIN_VALUE;
for(int x:a){
if(x>first){ second=first; first=x; }
else if(x>second && x!=first) second=x;
}
return second;
}

■ Interview Tip: x!=first handles duplicate max values correctly.

■ Reverse Array (in-place)


Logic:
• Two-pointer: swap arr[lo] & arr[hi], move towards centre.

• O(n) time, O(1) space — no extra array.

Code:
static void reverse(int[] a) {
int lo=0, hi=[Link]-1;
while(lo<hi){
int t=a[lo]; a[lo]=a[hi]; a[hi]=t;
lo++; hi--;
}
}

■ Interview Tip: Two-pointer is the expected answer — not a new array.


■ Remove Duplicates (sorted array)
Logic:
• Two-pointer: slow pointer j tracks unique position.

• Works in-place, O(n) time.

Code:
static int removeDup(int[] a) {
if([Link]==0) return 0;
int j=0;
for(int i=1;i<[Link];i++)
if(a[i]!=a[j]) a[++j]=a[i];
return j+1; // new length
}

■ Interview Tip: For unsorted: use LinkedHashSet to preserve order.

■ Linear Search & Binary Search


Logic:
• Linear: scan each element, O(n).

• Binary: sorted array only — compare mid, halve range, O(log n).

Code:
static int linear(int[] a,int t){
for(int i=0;i<[Link];i++) if(a[i]==t) return i;
return -1;
}
static int binary(int[] a,int t){
int lo=0,hi=[Link]-1;
while(lo<=hi){
int mid=lo+(hi-lo)/2;
if(a[mid]==t) return mid;
if(a[mid]<t) lo=mid+1; else hi=mid-1;
}
return -1;
}

■ Interview Tip: Use lo+(hi-lo)/2 NOT (lo+hi)/2 — avoids int overflow.


■ Rotate Array (left by k)
Logic:
• Reverse trick: reverse [0..k-1], reverse [k..n-1], reverse all.

• O(n) time, O(1) space.

Code:
static void rotateLeft(int[] a,int k){
k%=[Link];
rev(a,0,k-1); rev(a,k,[Link]-1); rev(a,0,[Link]-1);
}
static void rev(int[] a,int l,int r){
while(l<r){ int t=a[l];a[l]=a[r];a[r]=t;l++;r--; }
}

■ Interview Tip: The 3-reverse trick is the gold standard answer here.

4. String Problems
■ Reverse a String
Logic:
• [Link]() is the concise Java way.

• Manual: two-pointer on char array, same as array reverse.

Code:
static String reverseStr(String s){
return new StringBuilder(s).reverse().toString();
}
// Manual (shows understanding):
static String reverseManual(String s){
char[] c=[Link]();
int l=0,r=[Link]-1;
while(l<r){ char t=c[l];c[l]=c[r];c[r]=t;l++;r--; }
return new String(c);
}

■ Interview Tip: Show both — says you know the library AND the logic.
■ Palindrome String Check
Logic:
• Two-pointer from both ends — no extra space.

• Case-insensitive compare with toLowerCase().

Code:
static boolean isPalinStr(String s){
s=[Link]();
int l=0,r=[Link]()-1;
while(l<r) if([Link](l++)!=[Link](r--)) return false;
return true;
}

■ Interview Tip: Mention you handle case — interviewers often forget to specify.

■ Count Vowels & Consonants


Logic:
• Single pass, check if char is in 'aeiou'.

• Ignore non-alphabet characters cleanly.

Code:
static void countVC(String s){
s=[Link]();
int v=0,c=0;
for(char ch:[Link]()){
if("aeiou".indexOf(ch)>=0) v++;
else if(ch>='a'&&ch;<='z') c++;
}
[Link]("V:"+v+" C:"+c);
}

■ Remove Spaces & Character Frequency


Logic:
• Remove spaces: replaceAll(\"\\\\s\",\"\") or manual char filter.

• Frequency: int[26] array — index = ch-'a'.

Code:
static String removeSpaces(String s){
return [Link]("\\s","");
}
static void charFreq(String s){
int[] freq=new int[26];
for(char c:[Link]().toCharArray())
if(c>='a'&&c;<='z') freq[c-'a']++;
for(int i=0;i<26;i++)
if(freq[i]>0) [Link]((char)('a'+i)+":"+freq[i]);
}

■ Interview Tip: int[26] array is O(1) space — better than HashMap for a-z only.
5. Recursion (Basic Level)
■ Factorial
Logic:
• Base case: n<=1 → return 1.

• Recursive: n * factorial(n-1).

• Stack depth = n, so use iterative for large n.

Code:
static long factorial(int n){
return n<=1 ? 1 : n*factorial(n-1);
}

■ Interview Tip: Always mention stack overflow risk for large n.

■ Fibonacci
Logic:
• Naive recursion is O(2^n) — mention memoization fix.

• Iterative is O(n) time O(1) space — preferred in production.

Code:
// Recursive (simple, explain O(2^n) drawback):
static int fib(int n){ return n<=1?n:fib(n-1)+fib(n-2); }

// Iterative (O(n), O(1)):


static int fibIter(int n){
if(n<=1) return n;
int a=0,b=1;
for(int i=2;i<=n;i++){ int t=a+b; a=b; b=t; }
return b;
}

■ Interview Tip: Show both — give iterative as your 'optimised' answer.

■ Sum of First N Numbers (recursive)


Logic:
• Base: n==0 → 0. Recursive: n + sum(n-1).

• Also mention O(1) formula: n*(n+1)/2.

Code:
static int sumN(int n){ return n==0?0:n+sumN(n-1); }
// O(1) formula version:
static int sumFormula(int n){ return n*(n+1)/2; }

■ Interview Tip: Mentioning the formula instantly impresses.

6. Logic Building Problems


■ Swap Two Numbers (with & without temp)
Logic:
• With temp: safest, works for all types.

• Without temp: XOR swap — works only for integers.

• Arithmetic swap risks overflow — avoid.

Code:
// With temp:
int t=a; a=b; b=t;

// XOR (no temp, integers only):


a=a^b; b=a^b; a=a^b;

// Arithmetic (mention overflow risk):


a=a+b; b=a-b; a=a-b;

■ Interview Tip: XOR swap is the smart answer — mention it requires distinct variables.

■ Even / Odd Check


Logic:
• Bitwise AND with 1 is faster than modulo.

• n&1 == 0 → even; n&1 == 1 → odd.

Code:
static String evenOdd(int n){
return (n&1)==0 ? "Even" : "Odd";
}

■ Interview Tip: Bitwise over % → shows you think about low-level efficiency.

■ Leap Year Check


Logic:
• Divisible by 4 AND (not 100 OR divisible by 400).

• Order of conditions matters for short-circuit evaluation.

Code:
static boolean isLeap(int y){
return (y%4==0) && (y%100!=0 || y%400==0);
}

■ Interview Tip: 2000 is leap, 1900 is NOT — classic trick question.


■ Power of a Number (x^n)
Logic:
• Brute force: multiply x, n times — O(n).

• Fast power (binary exponentiation): O(log n).

• If n is even: x^n = (x^(n/2))^2.

• If n is odd: x^n = x * x^(n-1).

Code:
static long power(long x, int n){
long res=1;
while(n>0){
if((n&1)==1) res*=x;
x*=x;
n>>=1;
}
return res;
}

■ Interview Tip: Binary exponentiation = O(log n). Say this clearly.


Quick Reference — Complexity Cheatsheet
Problem Time Space Key Trick

Prime Check O(√n) O(1) Loop till i*i<=n

Palindrome Number O(log n) O(1) Reverse half

Armstrong O(d) O(1) d = digit count

GCD (Euclidean) O(log min) O(1) Recursion

LCM O(log min) O(1) a/gcd * b

Binary Search O(log n) O(1) mid = lo+(hi-lo)/2

Rotate Array O(n) O(1) 3-Reverse

Remove Dup (sorted) O(n) O(1) Two Pointer

Power (x^n) O(log n) O(1) Binary Exp

Fibonacci O(n) O(1) Iterative

Char Frequency O(n) O(1) int[26]

Remember da: Brute force = weak signal. Always state the optimal complexity and the trick behind it. Good luck Bubu!

You might also like