DSA Problems
==================
Section 1 : Logic Building
==================
1) Check Even and Odd
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
for(int i=0; i<[Link]; i++){
if(arr[i] % 2 == 0){
[Link](" Even : " + arr[i]);
} else {
[Link](" Odd : " + arr[i]);
}
}
}
Output : Odd : 1 Even : 2
2) Check IsPrime no or not
public static void main(String[] args) {
int n=13;
boolean isPrime = true;
if(n<=1){
isPrime=false;
} else {
for(int i=2; i<n; i++){
if(n % i == 0){
isPrime = false;
break;
}
}
}
[Link](isPrime);
}
Output = False
3) Factorial of Number
public static void main(String[] args) {
int n=4;
int fact =1;
for(int i=1; i<=n; i++){
fact = fact*i;
}
[Link]("fact of " + n + " : "+ fact);
}
Output : fact of 4 : 24
4) Fibonacci Series (n terms)
public static void main(String[] args) {
int n=5;
int a=0;
int b=1;
for(int i=0; i<n; i++){
[Link](a); //print current number
int temp = a+b; // next number
a = b; // shift a
b = temp; // shift b
}
}
Output : 0 1 1 2 3
5) Reverse a Number
public static void main(String[] args) {
int num = 1234;
int temp = num;
int rev=0, rem;
while(temp != 0){
rem = temp % 10;
rev = rev * 10 + rem;
temp = temp / 10;
}
[Link](rev);
}
Output :4321
6) Palindrome Number (252)
public class Main {
public static void main(String[] args) {
int num = 252; // number we want to check
int temp = num; // store num
int rev = 0, rem;
while (temp != 0) { // repeat until number becomes 0
rem = temp % 10; // get last rem (121 % 10 = 1)
rev = rev * 10 + rem; // build reverse number
temp = temp / 10; // remove last rem (121 / 10 = 12)
}
if (num == rev) { // compare original and reverse
[Link]("Palindrome");
} else {
[Link]("Not Palindrome");
}
}
}
eg. Example with n = 121
Start: n = 121, temp = 121, rev = 0
Loop 1: rem = 121 % 10 = 1
rev = 0 * 10 + 1 = 1
temp = 121 / 10 = 12
Loop 2: rem = 12 % 10 = 2
rev = 1 * 10 + 2 = 12
temp = 12 / 10 = 1
Loop 3: rem = 1 % 10 = 1
rev = 12 * 10 + 1 = 121
temp = 1 / 10 = 0 (loop ends)
Now rev = 121, which is same as n.
So → Palindrome ✅
7) Sum of Digit
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
int sum=0;
for(int i=0; i<[Link]; i++){
sum += arr[i];
}
[Link](sum);
}
Output = 15
8) Swap of Two number With temp and Without temp
public static void main(String[] args) {
int a=5, b=6, temp;
//Using Temp
temp = a;
a = b;
b = temp;
[Link](a + " " + b);
//Without Temp
a = a + b;
b = a - b;
a = a - b;
[Link](a + " " + b);
}
9) Greatest of Three number
public static void main(String[] args) {
int a=10, b=6, c=7;
#Normal approach
if(a >= b && a>= c){
[Link](a + " is greatest");
} else if (b >= a && b >= c){
[Link](b + " is greatest");
} else {
[Link](c + " is greatest");
}
#Using inbuilt function
int greatest = [Link](a, [Link](b,c));
[Link](greatest);
}
10) Armstrong number = 153 → 3 digits → 1³ + 5³ + 3³ = 1 + 125 +
27 = 153 ✅ Armstrong
public static void main(String[] args) {
int num = 153;
int original = num;
int sum = 0, rem;
while( num > 0){
rem = num % 10; // last digita rem
sum = sum + (rem * rem * rem); // for cube
num = num / 10; // remove last digit
}
if(sum == original){
[Link]("Armstrong number");
} else {
[Link]("Not a armstrong number");
}
}
Section 2 : String Problems
1) Reverse a String
#Normal approach
public static void main(String[] args) {
String str = "Pankaj";
String result = "";
for(int i=[Link]()-1; i>=0; i--){
result+=[Link](i);
}
[Link](result);
}
#Using function
public static void main(String[] args) {
String str = "Pankaj";
StringBuilder res = new StringBuilder(str);
[Link]([Link]());
}
2) Palindrome String
public static void main(String[] args) {
String str = "MAM";
StringBuilder rev = new StringBuilder(str).reverse();
if([Link]([Link]())){
[Link]("Palindrome");
} else {
[Link]("Not a Palindrome");
}
}
3) Count Vowels and Consonants
public static void main(String[] args) {
String str = "Pankaj";
str = [Link]();
int vowels = 0, consonants = 0;
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch ==
'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}
[Link]("Vowels: " + vowels + " Consonants: " +
consonants);
}
4) Find Duplicate Char in string
public static void main(String[] args) {
String str = "Programming";
char[] ch = [Link]();
for(int i=0; i<[Link]; i++){
for(int j=i+1; j<[Link]; j++){
if(ch[i]==ch[j]){
[Link](ch[i]);
break;
}
}
}
5) Remove Duplicate from String
public static void main(String[] args) {
String str = "Programming";
String result = "";
for(int i=0; i<[Link](); i++){
char ch = [Link](i);
//indexOf() is used for if not found return -1, so -1==-1 true
if([Link](ch) == -1){
result += ch;
}
}
[Link](result);
}
#Using Set
public static void main(String[] args) {
String str = "Programming";
Set<Character> ch = new LinkedHashSet<>(); // keeps order
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i)); // add each character
}
[Link](ch); // prints set of unique characters
}
6) Count Each Character Frequency
#Using Map
public static void main(String[] args) {
String str = "Programming";
Map<Character, Integer> mp = new HashMap<>();
// Count frequency
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
[Link](ch, [Link](ch, 0) + 1);
}
// Print frequency keySet() give keys of Map And
[Link]() give frequency(count) of that key
for (char ch : [Link]()) {
[Link](ch + " : " + [Link](ch));
}
}
#Using Stream API
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
String str = "programming";
var freq = [Link]()
// gives IntStream of chars
.mapToObj(c -> (char) c) // convert int -> char
.collect([Link](
[Link](), // group by character
[Link]() // count frequency
));
// Print result
[Link]((ch, count) -> [Link](ch + " :
" + count));
}
}
7) Anagram Check (Two strings have same characters with same
frequency, but maybe in different order )
import [Link];
public class Main {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
// Step 1: If lengths differ, not anagram
if ([Link]() != [Link]()) {
[Link]("Not Anagram");
return;
}
// Step 2: Convert to char array and sort
char[] arr1 = [Link]();
char[] arr2 = [Link]();
[Link](arr1);
[Link](arr2);
// Step 3: Compare sorted arrays
if ([Link](arr1, arr2)) {
[Link]("Anagram");
} else {
[Link]("Not Anagram");
}
}
}
8) Longest Word in Sentence
#Using Normal Approach
public static void main(String[] args) {
String sentence = "I love programming very much";
String[] words = [Link](" "); // split by space
String longest = "";
for (String word : words) {
if ([Link]() > [Link]()) {
longest = word;
}
}
[Link]("Longest word: " + longest);
}
#Using Stream API
public static void main(String[] args) {
String sentence = "Hi my name is Pankaj";
[Link]([Link](" "))
.max([Link](String::length))
.ifPresent(word -> [Link](word));
}
9) Capitalize First Letter of Each Word
#Using Normal Approach
public static void main(String[] args) {
String sentence = "Hi my name is pankaj";
String[] words = [Link](" ");
String result = "";
for(int i=0; i < [Link];i++){
if(!words[i].isEmpty()){
String word = words[i];
String Capatalize = [Link](0,1).toUpperCase()+
[Link](1).toLowerCase();
result += Capatalize + " ";
}
}
// option
sentence[0] = sentence[0].toUpperCase();
for(int i=1;i<[Link];i++)
{
if(sentence[i-1]==" ")
{
sentence[i]=sentence[i].toUpperCase();
}
}
[Link]([Link]());
}
#Using Stream API
public static void main(String[] args) {
String sentence = "Hi my name is pankaj";
[Link](
[Link]([Link](" "))
.map(word -> [Link](0,1).toUpperCase() +
[Link](1).toLowerCase())
.collect([Link](" "))
);
}
10) Pangram - a sentence that contains all 26 letters of English
alphabet at least once.
public static void main(String[] args) {
String sentence = "The quick brown fox jumps over the lazy
dog";
boolean isPangram = [Link]()
.chars() // stream of characters
.filter(Character::isLetter) // keep only letters
.mapToObj(c -> (char) c) // convert int → char
.collect([Link]()) // unique letters
.size() == 26; // must be 26
[Link](isPangram ? "Pangram" : "Not Pangram");
}
11) Word Count of String
#Normal Approach
public static void main(String[] args) {
String str = "Hi my name is pankaj"; //split("\\s+") →
splits on 1 or more spaces.
int count = [Link]().split("\\s+").length; // trim() →
removes spaces at start and end.
[Link]("Word Count : " + count);
}
#Using Stream API
public static void main(String[] args) {
String sentence = "Hi my name is Pankaj";
[Link]("Word count: " +
[Link]([Link]().split("\\s+")).count());
}
Section 3 : Array Problems
1) Find Max element in array
public static void main(String[] args) {
int[] arr = {2,3,1,5,6};
int max = arr[0];
for(int i=0; i<[Link]; i++){
if(arr[i] > max){
max=arr[i];
}
}
[Link](max);
}
2) Find Minimum Element
public static void main(String[] args) {
int[] arr = {2,3,1,5,6};
int min = arr[0];
for(int i=0; i<[Link]; i++){
if(arr[i] < min){
min=arr[i];
}
}
[Link](min);
}
3) Sum of All Elements
public static void main(String[] args) {
int[] arr = {2,3,1,5,6};
int sum=0;
for(int i=0; i<[Link]; i++){
sum+=arr[i];
}
[Link](sum);
}
4) Reverse Array
public static void main(String[] args) {
int[] arr = {2,3,1,5,6};
int temp;
for(int i=0, j=[Link]-1; i<j; i++, j--){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
[Link]([Link](arr));
}
#[Link](arr) → prints reference.
#[Link](arr) → prints actual values.
5) Search Element in Array
#If array is at any order sorted/unsorted : Linear Search
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int target = 30;
boolean found = false;
for (int i = 0; i < [Link]; i++) {
if (arr[i] == target) {
[Link]("Element found at index: " + i);
found = true;
break;
}
}
if (!found) {
[Link]("Element not found");
}
}
#If array is sorted : Binary Search
public class Main {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
int target = 4;
int left = 0;
int right = [Link] - 1;
boolean found = false;
while(left <= right){
int mid = (left + right) / 2;
if(arr[mid] == target){
[Link]("Found at index: " + mid);
found = true;
break;
} else if (target > arr[mid]){
left = mid + 1;
} else {
right = mid - 1;
}
}
if(!found){
[Link]("Element not found");
}
}
}
6) Second Largest Element
#Without Sorting
public static void main(String[] args) {
int[] arr = {10, 20, 50, 30 ,40};
int max = Integer.MIN_VALUE;
int second_max = Integer.MIN_VALUE;
for(int i=0; i<[Link]; i++){
if(arr[i] > max){
second_max = max;
max = arr[i];
} else if (arr[i] > second_max && arr[i] != max){
second_max = arr[i];
}
}
[Link](second_max);
#Using sorting
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
[Link](arr); // sorts in ascending order
[Link]("Secnd largest: " + arr[[Link] - 2]);
}
7) Print Duplicate element in Array
public static void main(String[] args) {
int[] arr = {10, 20, 50, 30, 20, 40};
for(int i=0; i<[Link]; i++){
for(int j=i+1; j<[Link]; j++){
if(arr[i] == arr[j]){
[Link](arr[j]);
}
}
}
8) Remove Duplicates from Sorted Array
public static void main(String[] args) {
int[] arr = {1, 1, 2, 2, 3, 4, 4, 5};
int n = [Link];
int j = 0; // index for unique elements
for (int i = 1; i < n; i++) {
if (arr[j] != arr[i]) { // if next element is different
j++;
arr[j] = arr[i]; // put unique element forward
}
}
// j+1 is the count of unique elements
[Link]("Unique elements: ");
for (int i = 0; i <= j; i++) {
[Link](arr[i] + " ");
}
}
9) Find Frequency of Each Element
public static void main(String[] args) {
int[] arr = {10, 20, 50, 30, 20, 40};
Map<Integer, Integer> freq = new HashMap<>();
for(int i=0; i<[Link];i++){
[Link](arr[i], [Link](arr[i],0)+1);
}
for(int key : [Link]()){
[Link](key + ":" +[Link](key));
}
}
#Using Stream API
public static void main(String[] args) {
int[] arr = {10, 20, 50, 30, 20, 40};
[Link](arr) //converts array to stream.
.boxed() //converts int → Integer (needed for Map).
.collect([Link](x -> x,
[Link]())) //groups by element and counts frequency.
.forEach((k, v) -> [Link](k + " : " + v));
//prints result.
}
10. Sort Array Bubble Sort
public static void main(String[] args) {
int[] arr = {10, 20, 50, 30, 40};
int temp=0;
for(int i=0; i<[Link]; i++){
for(int j=i+1; j<[Link]-1-i; j++){
//[Link]-1-i = last element is sort after every interation
if(arr[j] > arr[j+1]){ so avoid check last position
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}[Link]([Link](arr));
}
11) Left Rotate Array by 1
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int first = arr[0]; // save first element
for (int i = 0; i < [Link] - 1; i++) {
arr[i] = arr[i + 1]; // shift left
} 345
arr[[Link] - 1] = first; // put first at end
[Link]([Link](arr));
}
Common Recent Java Coding Questions
• Reverse a String in Java without using built-in
methods.
public static void main(String[] args) {
String str = "Pankaj";
String rev="";
for(int i=[Link]()-1; i>=0; i--){
rev += [Link](i);
}
[Link](rev);
}
• Check if a string is a palindrome.
public static void main(String[] args) {
String str = "madam";
String rev="";
for(int i=[Link]()-1; i>=0; i--){
rev += [Link](i);
}
if([Link](str)){
[Link]("Palindrome");
} else {
[Link]("Not Palindrome");
}
}
• Find duplicates in an array.
public static void main(String[] args) {
String str = "madam";
char[] ch = [Link]();
for(int i=0; i<[Link]; i++){
for(int j=i+1; j<[Link]; j++){
if(ch[i] == ch[j]){
[Link](ch[i]);
}
}
}
}
• Find missing number in an array containing numbers
1 to n.
public static void main(String[] args) {
//Find missing number in an array containing numbers 1 to n.
int[] arr = {2,3,1,5};
int n=5;
int total = n * (n+1) / 2;
int sum=0;
for(int i=0; i<[Link]; i++){
sum+=arr[i];
}
[Link](total - sum);
}
• Find the factorial of a number (using recursion or
iteration).
1. Iteration
public static void main(String[] args) {
//Find missing number in an array containing numbers 1 to n.
int n=5;
int fact=1;
for(int i=1; i<=n; i++){
fact *= i;
}
[Link](fact);
}
2. Recursion
public static int fact(int n){
if(n==0 || n==1){
return 1;
}
return n * fact(n - 1);
}
public static void main(String[] args) {
int n=5;
[Link](fact(n));
}
• Generate the Fibonacci series (iteratively and
recursively).
1. Iteration
public static void main(String[] args) {
int n=5;
int first=0;
int second=1;
for(int i=0; i<n; i++){
[Link](first);
int temp=first+second;
first = second;
second = temp;
}
}
2. Recursion
public static int fib(int n){
if(n==0) return 0;
if(n==1) return 1;
return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int n=5;
for(int i=0; i<n; i++){
[Link](fib(i));
}
}
• Swap two numbers without using a third variable.
public static void main(String[] args) {
int a=5; int b=6;
a = a + b;
b = a - b;
a = a - b;
[Link](a + " " + b);
}
• Find the largest and smallest elements in an array.
1. best way
public static void main(String[] args) {
int[] arr = {4,5,3,5,1,9};
int small = arr[0];
int large = arr[0];
for(int i=0; i<[Link]; i++){
if(arr[i] < small){
small = arr[i];
} else if (arr[i] > large){
large = arr[i];
}
}
[Link](small + " " + large);
}
2. Using Sorting
int[] arr = {4,5,3,5,1,9};
int temp=0;
for(int i=0; i<[Link]; i++){
for(int j=i+1; j<[Link]; j++){
if(arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
[Link]("Small:"+ arr[0] + "Largest:" + arr[[Link] -
1]);
• Search for an element in a rotated sorted array in
time.
A rotated sorted array is basically a sorted array shifted at some
pivot.
Example: [0,1,2,4,5,6,7] → rotated → [4,5,6,7,0,1,2]
Use modified binary search:
Find mid.
Check if left half is sorted.
If target lies in sorted half → search there.
Else → search in the other half.
public class RotatedArraySearch {
public static int search(int[] arr, int target) {
int left = 0, right = [Link] - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
// check if left half is sorted
if (arr[left] <= arr[mid]) {
if (target >= arr[left] && target < arr[mid]) {
right = mid - 1; // search left half
} else {
left = mid + 1; // search right half
}
}
// else right half is sorted
else {
if (target > arr[mid] && target <= arr[right]) {
left = mid + 1; // search right half
} else {
right = mid - 1; // search left half
}
}
}
return -1; // not found
}
public static void main(String[] args) {
int[] arr = {4, 5, 6, 7, 0, 1, 2};
int target = 0;
int index = search(arr, target);
[Link]("Element found at index: " + index);
}
}
• Sum of all numbers in an array (with/without
streams or functional style).
✅ 1. Using Loop (Normal way)
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : arr) {
sum += num;
}
[Link]("Sum = " + sum);
}
✅ 2. Using Streams (Functional Style, Java 8+)
public static void main(String[] args) {
int[] arr = {4, 5, 6, 7, 0, 1, 2};
int sum = [Link](arr).sum();
[Link](sum);
}
✅ 3. Using Streams with Reduce
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int sum = [Link](arr).reduce(0, (a, b) -> a + b);
[Link]("Sum = " + sum);
}
##reduce(0, (a, b) -> a + b)
means → “start with 0 and keep adding each element b to accumulator
a”.
• Reverse an array in place.
✅ Idea - Swap the first element with the last element, second with
second-last, keep going until the middle.
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int left = 0, right = [Link] - 1;
while (left < right) {
// swap
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
// print reversed array
for (int num : arr) {
[Link](num + " ");
}
}
• Find maximum subarray sum (Kadane’s Algorithm).
1. Using Inbuilt [Link]()
public static void main(String[] args) {
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int maxSoFar = arr[0];
int currentSum = arr[0];
for (int i = 1; i < [Link]; i++) {
// either start new subarray OR extend existing
currentSum = [Link](arr[i], currentSum + arr[i]);
maxSoFar = [Link](maxSoFar, currentSum);
}
[Link]("Maximum subarray sum = " + maxSoFar);
}
2. Using normal iteration
public static void main(String[] args) {
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int maxSoFar = arr[0];
int currentSum = arr[0];
int start = 0; // temp start
int end = 0; // final end
int tempStart = 0; // possible new start
for (int i = 1; i < [Link]; i++) {
// decide whether to start new subarray or continue
if (arr[i] > currentSum + arr[i]) {
currentSum = arr[i];
tempStart = i; // new subarray starts here
} else {
currentSum = currentSum + arr[i];
}
// update max
if (currentSum > maxSoFar) {
maxSoFar = currentSum;
start = tempStart;
end = i;
}
}
[Link]("Maximum subarray sum = " + maxSoFar);
[Link]("Subarray: ");
for (int i = start; i <= end; i++) {
[Link](arr[i] + " ");
}
}
• Merge overlapping intervals (advanced, common for experienced roles).
• Print all permutations of a string (recursive and iterative).
• Detect if a linked list has a cycle.
Advanced and Tricky Java Interview Tasks
• Create a thread-safe Singleton class (using Enum approach).
• Design a mini library management or banking system.
• Write a custom class loader.
• Implement a vending machine design with code.
• Circular array rotation with efficient queries.
• Return an MD5 hash of a string.
• Implement merge of two sorted arrays.
• Find all unique elements present in either of two arrays (merge names
problem).