[go: up one dir, main page]

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

? Coding Questions in Java

The document provides a comprehensive list of coding questions categorized into basic, intermediate, and advanced levels, along with Java solutions for each question. It includes examples of coding tasks such as printing natural numbers, implementing a voting system, and performing arithmetic operations, as well as more complex problems like finding Armstrong numbers and converting number systems. Additionally, it mentions upcoming recursion problems and offers to solve them in Java.
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 views17 pages

? Coding Questions in Java

The document provides a comprehensive list of coding questions categorized into basic, intermediate, and advanced levels, along with Java solutions for each question. It includes examples of coding tasks such as printing natural numbers, implementing a voting system, and performing arithmetic operations, as well as more complex problems like finding Armstrong numbers and converting number systems. Additionally, it mentions upcoming recursion problems and offers to solve them in Java.
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/ 17

1.

Basic Coding Questions:


Print "Hello World."
Print the first N natural numbers.
Create a voting system program.
Check if a number is positive or negative.
Perform all basic arithmetic operations.
Check if a number is even or odd.
Implement a grading scheme for students.
Round off a number.
Calculate the square root and cube root of a number.
Print multiples (table) of a number.
Find the greatest of two numbers.
Find the greatest of three numbers.
Calculate Nth power of a number.
Learn break and continue statements.
Use a switch statement for multiple conditions.
Implement pass-by-value, pass-by-reference, and pass-by-pointer.
Implement and print 1D and 2D arrays.

2. Intermediate Coding Questions (Numbers):


Print the first N natural numbers in reverse order.
Sum the first N natural numbers.
Calculate the sum of numbers in a given range.
Check if a year is a leap year or not.
Determine if a number is prime.
Print all prime numbers in a given range.
Calculate the sum of digits of a number.
Reverse a number.
Check if a number is a palindrome.

3. Advanced Coding Questions (Numbers):


Implement Armstrong Number logic.
Find Armstrong numbers in a given range.
Print the prime factors of a number.
Calculate the HCF and LCM of two numbers.
Convert between Binary, Octal, Hexadecimal, and Decimal systems.

Nice👍 You’ve built a progressive coding question list from basics → intermediate → advanced. I’ll
organize it clearly and also give you hints / solution approach (in Java, since you asked about Java
earlier).

📘 Coding Questions in Java


1. Basic Coding Questions
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/17
1. Print "Hello World."

java

System.out.println("Hello World");

2. Print the first N natural numbers


→ Use a loop (for / while).

3. Create a voting system program


→ Input age, check >=18.

4. Check if a number is positive or negative


→ Use if-else.
5. Perform all basic arithmetic operations
→ Addition, subtraction, multiplication, division, modulus.

6. Check if a number is even or odd


→ num % 2 == 0.

7. Implement a grading scheme for students


→ if-else or switch for marks.
8. Round off a number
→ Use Math.round().

9. Calculate the square root and cube root of a number


→ Math.sqrt(), Math.cbrt().

10. Print multiples (table) of a number


→ Loop × multiplication.

11. Find the greatest of two numbers


→ if-else or Math.max().

12. Find the greatest of three numbers


→ Nested if-else or Math.max() twice.
13. Calculate Nth power of a number
→ Math.pow(base, exp).

14. Learn break and continue statements


→ In loops, skip (continue) or exit (break).

15. Use a switch statement for multiple conditions


→ Example: menu-driven calculator.

16. Implement pass-by-value, pass-by-reference, and pass-by-pointer


In Java, only pass-by-value exists (even for objects).

You can simulate reference via objects.

17. Implement and print 1D and 2D arrays


→ Loop through arrays with nested loops for 2D.

2. Intermediate Coding Questions (Numbers)


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/17
1. Print the first N natural numbers in reverse order
→ Loop from N down to 1.

2. Sum the first N natural numbers


→ Formula: n*(n+1)/2 OR loop.

3. Calculate the sum of numbers in a given range


→ Loop from start → end.
4. Check if a year is a leap year or not
→ (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0).
5. Determine if a number is prime
→ Check divisibility till sqrt(n).

6. Print all prime numbers in a given range


→ Loop + prime check function.

7. Calculate the sum of digits of a number


→ %10 and /10 trick.

8. Reverse a number
→ Extract digits and rebuild.
9. Check if a number is a palindrome
→ Compare with reversed number.

3. Advanced Coding Questions (Numbers)


1. Implement Armstrong Number logic
→ Sum of cubes (or nth power) of digits = original number.

2. Find Armstrong numbers in a given range


→ Loop + Armstrong check.

3. Print the prime factors of a number


→ Divide by primes till n==1.

4. Calculate the HCF and LCM of two numbers

HCF → Euclidean Algorithm


LCM → (a*b)/HCF
5. Convert between Binary, Octal, Hexadecimal, and Decimal systems
→ Use Integer.toBinaryString(n), Integer.parseInt(str, base) etc.

👉 Do you want me to start solving all these one by one in Java (full code with explanation) or
should I first make a single big Java file where all programs are kept separately (like a practice set)?

solve all in java

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/17
Perfect ✅ Let’s solve all of them in Java.
Since the list is very long (basic → intermediate → advanced), the cleanest way is to create a Practice Set
where each question is a separate method, and you can call whichever you want from main().

I’ll structure the solutions into three classes:

BasicQuestions

IntermediateQuestions

AdvancedQuestions

📌 Full Java Code – All Questions


java

import java.util.Scanner;

class BasicQuestions {
Scanner sc = new Scanner(System.in);

// 1. Print Hello World


void helloWorld() {
System.out.println("Hello World");
}

// 2. Print first N natural numbers


void printNaturalNumbers(int n) {
for (int i = 1; i <= n; i++) {
System.out.print(i + " ");
}
System.out.println();
}

// 3. Voting System
void votingSystem(int age) {
if (age >= 18) System.out.println("Eligible to vote.");
else System.out.println("Not eligible to vote.");
}

// 4. Positive or Negative
void checkNumber(int num) {
if (num > 0) System.out.println("Positive");
else if (num < 0) System.out.println("Negative");
else System.out.println("Zero");
}

// 5. Basic Arithmetic
void arithmeticOps(int a, int b) {
System.out.println("Sum = " + (a + b));
System.out.println("Diff = " + (a - b));
System.out.println("Product = " + (a * b));
System.out.println("Quotient = " + (a / b));
System.out.println("Remainder = " + (a % b));
}

// 6. Even or Odd
void evenOdd(int num) {
System.out.println((num % 2 == 0) ? "Even" : "Odd");
}

// 7. Grading Scheme
void grading(int marks) {
if (marks >= 90) System.out.println("A");
else if (marks >= 75) System.out.println("B");
else if (marks >= 50) System.out.println("C");
else System.out.println("Fail");
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/17
// 8. Round off
void roundNumber(double num) {
System.out.println("Rounded: " + Math.round(num));
}

// 9. Square root and cube root


void roots(double num) {
System.out.println("Square Root = " + Math.sqrt(num));
System.out.println("Cube Root = " + Math.cbrt(num));
}

// 10. Multiplication table


void table(int n) {
for (int i = 1; i <= 10; i++) {
System.out.println(n + " x " + i + " = " + (n * i));
}
}

// 11. Greatest of two


void greatestTwo(int a, int b) {
System.out.println("Greatest: " + Math.max(a, b));
}

// 12. Greatest of three


void greatestThree(int a, int b, int c) {
System.out.println("Greatest: " + Math.max(a, Math.max(b, c)));
}

// 13. Nth power


void power(int base, int exp) {
System.out.println(base + "^" + exp + " = " + Math.pow(base, exp));
}

// 14. Break and Continue


void breakContinue() {
for (int i = 1; i <= 10; i++) {
if (i == 5) continue; // skip 5
if (i == 8) break; // stop at 8
System.out.print(i + " ");
}
System.out.println();
}

// 15. Switch Statement


void switchCalc(int a, int b, char op) {
switch (op) {
case '+': System.out.println(a + b); break;
case '-': System.out.println(a - b); break;
case '*': System.out.println(a * b); break;
case '/': System.out.println(a / b); break;
default: System.out.println("Invalid Operator");
}
}

// 16. Pass by value (Java is always pass by value)


void passByValue(int x) {
x = x + 10;
System.out.println("Inside function: " + x);
}

// 17. Arrays
void arraysDemo() {
int[] arr1D = {1, 2, 3, 4, 5};
System.out.println("1D Array:");
for (int x : arr1D) System.out.print(x + " ");
System.out.println();

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


System.out.println("2D Array:");
for (int i = 0; i < arr2D.length; i++) {
for (int j = 0; j < arr2D[i].length; j++) {
System.out.print(arr2D[i][j] + " ");
}
System.out.println();
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/17
}
}
}

class IntermediateQuestions {
// 1. Reverse natural numbers
void reverseNatural(int n) {
for (int i = n; i >= 1; i--) System.out.print(i + " ");
System.out.println();
}

// 2. Sum first N
void sumFirstN(int n) {
int sum = n * (n + 1) / 2;
System.out.println("Sum = " + sum);
}

// 3. Sum in range
void sumRange(int a, int b) {
int sum = 0;
for (int i = a; i <= b; i++) sum += i;
System.out.println("Sum = " + sum);
}

// 4. Leap year
void leapYear(int year) {
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
System.out.println("Leap Year");
else System.out.println("Not a Leap Year");
}

// 5. Prime check
boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++)
if (n % i == 0) return false;
return true;
}

// 6. Primes in range
void primesInRange(int a, int b) {
for (int i = a; i <= b; i++)
if (isPrime(i)) System.out.print(i + " ");
System.out.println();
}

// 7. Sum of digits
void sumDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
System.out.println("Sum of Digits = " + sum);
}

// 8. Reverse number
void reverseNumber(int n) {
int rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
System.out.println("Reversed = " + rev);
}

// 9. Palindrome number
void palindrome(int n) {
int original = n, rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
if (original == rev) System.out.println("Palindrome");
else System.out.println("Not Palindrome");
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/17
}
}

class AdvancedQuestions {
// 1. Armstrong number
boolean isArmstrong(int n) {
int sum = 0, temp = n;
int digits = String.valueOf(n).length();
while (temp > 0) {
int d = temp % 10;
sum += Math.pow(d, digits);
temp /= 10;
}
return sum == n;
}

// 2. Armstrong numbers in range


void armstrongInRange(int a, int b) {
for (int i = a; i <= b; i++)
if (isArmstrong(i)) System.out.print(i + " ");
System.out.println();
}

// 3. Prime factors
void primeFactors(int n) {
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
System.out.print(i + " ");
n /= i;
}
}
System.out.println();
}

// 4. HCF and LCM


int hcf(int a, int b) {
if (b == 0) return a;
return hcf(b, a % b);
}

void hcfLcm(int a, int b) {


int h = hcf(a, b);
int l = (a * b) / h;
System.out.println("HCF = " + h + ", LCM = " + l);
}

// 5. Number system conversions


void conversions(int n) {
System.out.println("Binary: " + Integer.toBinaryString(n));
System.out.println("Octal: " + Integer.toOctalString(n));
System.out.println("Hex: " + Integer.toHexString(n));
}
}

public class PracticeSet {


public static void main(String[] args) {
BasicQuestions b = new BasicQuestions();
IntermediateQuestions i = new IntermediateQuestions();
AdvancedQuestions a = new AdvancedQuestions();

// Example calls
b.helloWorld();
b.printNaturalNumbers(10);
b.votingSystem(20);
b.arithmeticOps(10, 3);
b.arraysDemo();

i.reverseNatural(5);
i.primesInRange(10, 30);
i.palindrome(121);

a.armstrongInRange(1, 500);
a.hcfLcm(12, 18);
a.conversions(255);

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/17
}
}

✅ This covers all 26 questions you listed.


You just call the method you want in .
main()

👉 Do you want me to also separate each program into its own standalone file (with main inside
each) so you can run them one by one, instead of a single big PracticeSet?

4. Recursion:
Represent the number of pairs of parentheses.
Find the factorial of a number.
Generate all palindromic partitions of a string.
Count elements in an array divisible by K.
Sort a stack using recursion.
Generate all subsets of a set.
Find unique permutations of an array.
Remove adjacent duplicate characters recursively.
Calculate the Nth term of a series using recursion.

Perfect 🚀 You’re now moving into Recursion problems — these are slightly advanced because they
need careful thinking (base case + recursive case).
I’ll solve all 9 recursion questions in Java for you, same style as before (methods grouped under a
class).

📌 Java Code – Recursion Problems


java

import java.util.*;

class RecursionProblems {

// 1. Represent the number of pairs of parentheses (Catalan numbers)


// Cn = (2n)! / ((n+1)! * n!)
long catalan(int n) {
if (n <= 1) return 1;
long res = 0;
for (int i = 0; i < n; i++) {
res += catalan(i) * catalan(n - 1 - i);
}
return res;
}

// 2. Factorial of a number
long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}

// 3. Generate all palindromic partitions of a string


void palindromicPartitions(String s) {

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/17
List<List<String>> result = new ArrayList<>();
backtrackPalin(s, 0, new ArrayList<>(), result);
System.out.println(result);
}

private void backtrackPalin(String s, int start, List<String> curr, List<List<String>> res)


{
if (start == s.length()) {
res.add(new ArrayList<>(curr));
return;
}
for (int end = start; end < s.length(); end++) {
if (isPalindrome(s, start, end)) {
curr.add(s.substring(start, end + 1));
backtrackPalin(s, end + 1, curr, res);
curr.remove(curr.size() - 1);
}
}
}

private boolean isPalindrome(String s, int l, int r) {


while (l < r) {
if (s.charAt(l++) != s.charAt(r--)) return false;
}
return true;
}

// 4. Count elements divisible by K in an array


int countDivisible(int[] arr, int k, int idx) {
if (idx == arr.length) return 0;
int count = (arr[idx] % k == 0) ? 1 : 0;
return count + countDivisible(arr, k, idx + 1);
}

// 5. Sort a stack using recursion


void sortStack(Stack<Integer> stack) {
if (!stack.isEmpty()) {
int top = stack.pop();
sortStack(stack);
insertSorted(stack, top);
}
}

private void insertSorted(Stack<Integer> stack, int val) {


if (stack.isEmpty() || stack.peek() <= val) {
stack.push(val);
return;
}
int top = stack.pop();
insertSorted(stack, val);
stack.push(top);
}

// 6. Generate all subsets of a set


void subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrackSubsets(nums, 0, new ArrayList<>(), result);
System.out.println(result);
}

private void backtrackSubsets(int[] nums, int start, List<Integer> curr, List<List<Integer>>


res) {
res.add(new ArrayList<>(curr));
for (int i = start; i < nums.length; i++) {
curr.add(nums[i]);
backtrackSubsets(nums, i + 1, curr, res);
curr.remove(curr.size() - 1);
}
}

// 7. Find unique permutations of an array


void uniquePermutations(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
boolean[] used = new boolean[nums.length];
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/17
backtrackPerm(nums, new ArrayList<>(), result, used);
System.out.println(result);
}

private void backtrackPerm(int[] nums, List<Integer> curr, List<List<Integer>> res,


boolean[] used) {
if (curr.size() == nums.length) {
res.add(new ArrayList<>(curr));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) continue;
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue; // skip duplicates
used[i] = true;
curr.add(nums[i]);
backtrackPerm(nums, curr, res, used);
curr.remove(curr.size() - 1);
used[i] = false;
}
}

// 8. Remove adjacent duplicate characters recursively


String removeAdjacent(String s) {
if (s.length() <= 1) return s;
if (s.charAt(0) == s.charAt(1)) {
int i = 1;
while (i < s.length() && s.charAt(i) == s.charAt(0)) i++;
return removeAdjacent(s.substring(i));
} else {
return s.charAt(0) + removeAdjacent(s.substring(1));
}
}

// 9. Calculate the Nth term of a series using recursion (Example: Fibonacci)


int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

public class RecursionSet {


public static void main(String[] args) {
RecursionProblems rp = new RecursionProblems();

// 1. Catalan numbers
System.out.println("Catalan(3): " + rp.catalan(3));

// 2. Factorial
System.out.println("Factorial(5): " + rp.factorial(5));

// 3. Palindromic partitions
rp.palindromicPartitions("aab");

// 4. Count divisible
int[] arr = {2, 4, 5, 6, 10};
System.out.println("Divisible by 2: " + rp.countDivisible(arr, 2, 0));

// 5. Sort stack
Stack<Integer> st = new Stack<>();
st.push(3); st.push(1); st.push(4); st.push(2);
rp.sortStack(st);
System.out.println("Sorted stack: " + st);

// 6. Subsets
rp.subsets(new int[]{1, 2, 3});

// 7. Unique permutations
rp.uniquePermutations(new int[]{1, 1, 2});

// 8. Remove adjacent duplicates


System.out.println("Removed Adjacent: " + rp.removeAdjacent("aabbccddeee"));

// 9. Fibonacci
System.out.println("Fibonacci(6): " + rp.fibonacci(6));
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/17
}
}

✅ This file RecursionSet.java covers all 9 recursion problems you listed.

Catalan numbers (for parentheses count)


Factorial

Palindromic partitions

Divisible count
Stack sorting

Subsets generation

Unique permutations
Removing adjacent duplicates

Fibonacci (Nth term of a series)

Do you want me to also include recursion-based versions of earlier problems (like sum of digits,
reverse number, palindrome check, gcd etc.), or keep recursion only for this new set?

5. Arrays:
Perform linear search.
Find the smallest and second smallest elements in an array.
Reverse an array.
Sort an array using Bubble Sort.
Count distinct elements in an array.
Find the kth smallest and largest elements in an array.
Move all negative elements to one side of the array.
Find the union and intersection of two arrays.
Rotate an array cyclically by one.
Find the largest sum contiguous subarray (Kadane’s Algorithm).
Solve the trapping rainwater problem.
Solve the chocolate distribution problem.
Merge two sorted arrays without extra space.
Find the minimum number of jumps to reach the end of an array.

🔥 Great — you’re systematically covering DSA topics now. Arrays are the backbone of most DSA
problems.
I’ll solve all 13 array problems in Java, keeping them inside a single ArrayProblems class with clean
methods. Each method can be tested from main().

📌 Java Code – Array Problems


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/17
java

import java.util.*;

class ArrayProblems {

// 1. Linear Search
int linearSearch(int[] arr, int key) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key) return i;
}
return -1;
}

// 2. Smallest & Second Smallest


void smallestTwo(int[] arr) {
int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;
for (int num : arr) {
if (num < first) {
second = first;
first = num;
} else if (num < second && num != first) {
second = num;
}
}
System.out.println("Smallest = " + first + ", Second Smallest = " + second);
}

// 3. Reverse Array
void reverseArray(int[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++; r--;
}
System.out.println("Reversed: " + Arrays.toString(arr));
}

// 4. Bubble Sort
void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-1-i; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.println("Sorted: " + Arrays.toString(arr));
}

// 5. Count distinct elements


void countDistinct(int[] arr) {
HashSet<Integer> set = new HashSet<>();
for (int num : arr) set.add(num);
System.out.println("Distinct Count = " + set.size());
}

// 6. Kth Smallest and Largest


void kthSmallestLargest(int[] arr, int k) {
Arrays.sort(arr);
System.out.println(k + "th Smallest = " + arr[k-1]);
System.out.println(k + "th Largest = " + arr[arr.length-k]);
}

// 7. Move negatives to one side


void moveNegatives(int[] arr) {
int l = 0, r = arr.length - 1;
while (l <= r) {
if (arr[l] < 0 && arr[r] >= 0) {
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/17
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++; r--;
}
if (arr[l] >= 0) l++;
if (arr[r] < 0) r--;
}
System.out.println("Negatives moved: " + Arrays.toString(arr));
}

// 8. Union and Intersection


void unionIntersection(int[] arr1, int[] arr2) {
HashSet<Integer> union = new HashSet<>();
HashSet<Integer> inter = new HashSet<>();
for (int x : arr1) union.add(x);
for (int x : arr2) {
if (union.contains(x)) inter.add(x);
union.add(x);
}
System.out.println("Union: " + union);
System.out.println("Intersection: " + inter);
}

// 9. Rotate array by one


void rotateByOne(int[] arr) {
int n = arr.length;
int last = arr[n-1];
for (int i = n-1; i > 0; i--) arr[i] = arr[i-1];
arr[0] = last;
System.out.println("Rotated: " + Arrays.toString(arr));
}

// 10. Largest Sum Subarray (Kadane)


void kadane(int[] arr) {
int maxSoFar = arr[0], curr = arr[0];
for (int i = 1; i < arr.length; i++) {
curr = Math.max(arr[i], curr + arr[i]);
maxSoFar = Math.max(maxSoFar, curr);
}
System.out.println("Max Subarray Sum = " + maxSoFar);
}

// 11. Trapping Rainwater


void trappingRainwater(int[] height) {
int n = height.length;
int[] left = new int[n];
int[] right = new int[n];
left[0] = height[0];
for (int i = 1; i < n; i++) left[i] = Math.max(left[i-1], height[i]);
right[n-1] = height[n-1];
for (int i = n-2; i >= 0; i--) right[i] = Math.max(right[i+1], height[i]);
int water = 0;
for (int i = 0; i < n; i++) water += Math.min(left[i], right[i]) - height[i];
System.out.println("Trapped Water = " + water);
}

// 12. Chocolate Distribution Problem


void chocolateDistribution(int[] arr, int m) {
Arrays.sort(arr);
int minDiff = Integer.MAX_VALUE;
for (int i = 0; i+m-1 < arr.length; i++) {
int diff = arr[i+m-1] - arr[i];
minDiff = Math.min(minDiff, diff);
}
System.out.println("Minimum Difference = " + minDiff);
}

// 13. Merge two sorted arrays without extra space


void mergeSortedArrays(int[] arr1, int[] arr2) {
int n = arr1.length, m = arr2.length;
int i = n-1, j = 0;
while (i >= 0 && j < m) {
if (arr1[i] > arr2[j]) {
int temp = arr1[i];
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/17
arr1[i] = arr2[j];
arr2[j] = temp;
}
i--; j++;
}
Arrays.sort(arr1);
Arrays.sort(arr2);
System.out.println("Merged A1: " + Arrays.toString(arr1));
System.out.println("Merged A2: " + Arrays.toString(arr2));
}

// 14. Minimum Jumps to reach end


void minJumps(int[] arr) {
if (arr.length <= 1) {
System.out.println("Min Jumps = 0");
return;
}
if (arr[0] == 0) {
System.out.println("Not Possible");
return;
}
int maxReach = arr[0];
int steps = arr[0];
int jumps = 1;
for (int i = 1; i < arr.length; i++) {
if (i == arr.length - 1) {
System.out.println("Min Jumps = " + jumps);
return;
}
maxReach = Math.max(maxReach, i + arr[i]);
steps--;
if (steps == 0) {
jumps++;
if (i >= maxReach) {
System.out.println("Not Possible");
return;
}
steps = maxReach - i;
}
}
}
}

public class ArraySet {


public static void main(String[] args) {
ArrayProblems ap = new ArrayProblems();

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


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

// Examples
System.out.println("Linear Search for 6: " + ap.linearSearch(arr, 6));
ap.smallestTwo(arr);
ap.reverseArray(arr2.clone());
ap.bubbleSort(arr2.clone());
ap.countDistinct(arr);
ap.kthSmallestLargest(arr2.clone(), 2);
ap.moveNegatives(arr.clone());
ap.unionIntersection(new int[]{1,2,3}, new int[]{2,3,4});
ap.rotateByOne(arr2.clone());
ap.kadane(new int[]{-2,1,-3,4,-1,2,1,-5,4});
ap.trappingRainwater(new int[]{3,0,0,2,0,4});
ap.chocolateDistribution(new int[]{7,3,2,4,9,12,56}, 3);
ap.mergeSortedArrays(new int[]{1,5,9,10,15,20}, new int[]{2,3,8,13});
ap.minJumps(new int[]{1,3,5,8,9,2,6,7,6,8,9});
}
}

✅ This covers all 13 array-based problems you asked for.


Each method is self-contained and can be tested independently.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/17
👉 Do you want me to continue in the same style for Strings next (common string problems like
anagrams, longest substring, pattern search, etc.)?

6. Strings:
Check if a character is a vowel or consonant.
Check if a character is an alphabet or not.
Find the ASCII value of a character.
Calculate the length of a string without strlen().
Toggle characters in a string (uppercase to lowercase and vice versa).
Count the number of vowels in a string.
Remove vowels from a string.
Check if a string is a palindrome.
Reverse a string.
Count the frequency of characters in a string.
Replace a substring in a string.
Check if two strings are anagrams.
Print all permutations of a string in lexicographical order.

Perfect 👍
Let’s continue with Strings in Java.
Below are solutions for all your string-based coding questions:

6. Strings (Java Solutions)


java

import java.util.*;

public class StringProblems {

// 1. Check if a character is a vowel or consonant


static void checkVowelOrConsonant(char c) {
c = Character.toLowerCase(c);
if ("aeiou".indexOf(c) != -1)
System.out.println(c + " is a Vowel");
else if (Character.isAlphabetic(c))
System.out.println(c + " is a Consonant");
else
System.out.println(c + " is not an alphabet");
}

// 2. Check if a character is an alphabet or not


static void checkAlphabet(char c) {
if (Character.isAlphabetic(c))
System.out.println(c + " is an Alphabet");
else
System.out.println(c + " is not an Alphabet");
}

// 3. Find ASCII value of a character


static void asciiValue(char c) {
System.out.println("ASCII value of " + c + " = " + (int) c);
}

// 4. Calculate length of string without strlen()


static int stringLength(String str) {
int count = 0;
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/17
for (char c : str.toCharArray())
count++;
return count;
}

// 5. Toggle characters (upper <-> lower)


static String toggleCase(String str) {
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (Character.isUpperCase(c))
sb.append(Character.toLowerCase(c));
else if (Character.isLowerCase(c))
sb.append(Character.toUpperCase(c));
else
sb.append(c);
}
return sb.toString();
}

// 6. Count vowels in string


static int countVowels(String str) {
int count = 0;
for (char c : str.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(c) != -1)
count++;
}
return count;
}

// 7. Remove vowels from string


static String removeVowels(String str) {
return str.replaceAll("[AEIOUaeiou]", "");
}

// 8. Check if string is palindrome


static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j) {
if (str.charAt(i) != str.charAt(j))
return false;
i++;
j--;
}
return true;
}

// 9. Reverse a string
static String reverseString(String str) {
return new StringBuilder(str).reverse().toString();
}

// 10. Count frequency of characters


static void charFrequency(String str) {
Map<Character, Integer> freq = new HashMap<>();
for (char c : str.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
System.out.println(freq);
}

// 11. Replace substring


static String replaceSubstring(String str, String oldSub, String newSub) {
return str.replace(oldSub, newSub);
}

// 12. Check if two strings are anagrams


static boolean areAnagrams(String s1, String s2) {
char[] a = s1.replaceAll("\\s", "").toLowerCase().toCharArray();
char[] b = s2.replaceAll("\\s", "").toLowerCase().toCharArray();
Arrays.sort(a);
Arrays.sort(b);
return Arrays.equals(a, b);
}

// 13. Print all permutations of string in lexicographical order


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/17
static void permutations(String str) {
TreeSet<String> set = new TreeSet<>();
permute("", str, set);
for (String s : set)
System.out.println(s);
}

static void permute(String prefix, String str, Set<String> set) {


if (str.length() == 0) {
set.add(prefix);
} else {
for (int i = 0; i < str.length(); i++) {
permute(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i + 1),
set);
}
}
}

// MAIN method for testing


public static void main(String[] args) {
checkVowelOrConsonant('a');
checkAlphabet('1');
asciiValue('A');
System.out.println("Length = " + stringLength("hello"));
System.out.println("Toggle = " + toggleCase("Hello123"));
System.out.println("Vowels = " + countVowels("education"));
System.out.println("Removed Vowels = " + removeVowels("education"));
System.out.println("Palindrome? " + isPalindrome("madam"));
System.out.println("Reverse = " + reverseString("hello"));
charFrequency("hello");
System.out.println("Replace = " + replaceSubstring("hello world", "world", "Java"));
System.out.println("Anagrams? " + areAnagrams("listen", "silent"));
System.out.println("Permutations of ABC:");
permutations("ABC");
}
}

✅ This Java file includes all 13 string problems in one place.


Do you want me to also merge all categories (basic, arrays, recursion, etc.) into one master Java
program with a menu system, so you can run and choose problems interactively?

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/17

You might also like