Programming - jiquest

add

#

Programming


  

Basic Logic and Control Structures

  1. Write a program to check if a number is even or odd.
  2. Write a program to find the largest of three numbers.
  3. Write a program to check if a given year is a leap year.
  4. Write a program to calculate the factorial of a number.
  5. Write a program to generate the Fibonacci series up to a given number.
  6. Write a program to reverse a given integer number.
  7. Write a program to check if a number is a palindrome.
  8. Write a program to find the greatest common divisor (GCD) of two numbers.
  9. Write a program to find the least common multiple (LCM) of two numbers.
  10. Write a program to print the prime numbers up to a given number.
  11. Write a program to check if a number is prime.
  12. Write a program to calculate the sum of digits of a number.
  13. Write a program to calculate the power of a number using recursion.
  14. Write a program to swap two numbers without using a third variable.
  15. Write a program to find the sum of the first N natural numbers.
  16. Write a program to check if a number is an Armstrong number.
  17. Write a program to check if a number is a perfect number.
  18. Write a program to find the average of N numbers.
  19. Write a program to find the second largest number in an array.
  20. Write a program to find the sum of all prime numbers up to a given number.

Array and String Manipulation

  1. Write a program to reverse an array.
  2. Write a program to find the maximum and minimum elements in an array.
  3. Write a program to sort an array using bubble sort.
  4. Write a program to sort an array using insertion sort.
  5. Write a program to find the missing number in an array of integers.
  6. Write a program to remove duplicates from an array.
  7. Write a program to find the common elements between two arrays.
  8. Write a program to merge two sorted arrays.
  9. Write a program to rotate an array by K positions.
  10. Write a program to find the frequency of each element in an array.
  11. Write a program to check if a string is a palindrome.
  12. Write a program to count the number of vowels and consonants in a string.
  13. Write a program to reverse a string.
  14. Write a program to find the first non-repeated character in a string.
  15. Write a program to check if two strings are anagrams of each other.
  16. Write a program to find all permutations of a given string.
  17. Write a program to remove all white spaces from a string.
  18. Write a program to check if a string contains only digits.
  19. Write a program to find the longest substring without repeating characters.
  20. Write a program to count the occurrence of each character in a string.

Searching and Sorting Algorithms

  1. Write a program to implement binary search.
  2. Write a program to implement linear search.
  3. Write a program to sort an array using selection sort.
  4. Write a program to sort an array using merge sort.
  5. Write a program to sort an array using quick sort.
  6. Write a program to sort an array using heap sort.
  7. Write a program to find the kth smallest/largest element in an array.
  8. Write a program to search an element in a rotated sorted array.
  9. Write a program to implement the Dutch National Flag problem (sort an array of 0s, 1s, and 2s).
  10. Write a program to find the intersection of two sorted arrays.

Mathematical and Number-Based Problems

  1. Write a program to check if a number is a power of two.
  2. Write a program to find the square root of a number without using a built-in function.
  3. Write a program to find the nth Fibonacci number using dynamic programming.
  4. Write a program to generate all prime numbers less than N using the Sieve of Eratosthenes.
  5. Write a program to calculate the binomial coefficient.
  6. Write a program to find the sum of all digits until the sum becomes a single digit.
  7. Write a program to find the sum of all even numbers up to a given number.
  8. Write a program to print the pascal triangle.
  9. Write a program to find the sum of the first N Fibonacci numbers.
  10. Write a program to check if a number is a perfect square.


1. Write a program to check if a number is even or odd.


import java.util.Scanner;

public class EvenOddCheck {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int number = scanner.nextInt();

    if (number % 2 == 0) {
      System.out.println(number + " is even.");
    } else {
      System.out.println(number + " is odd.");
    }

    scanner.close();
  }
}


2. Write a program to find the largest of three numbers.

import java.util.Scanner;

public class LargestOfThree {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input three numbers
    System.out.print("Enter the first number: ");
    int num1 = scanner.nextInt();

    System.out.print("Enter the second number: ");
    int num2 = scanner.nextInt();

    System.out.print("Enter the third number: ");
    int num3 = scanner.nextInt();

    // Determine the largest number
    int largest;

    if (num1 >= num2 && num1 >= num3) {
      largest = num1;
    } else if (num2 >= num1 && num2 >= num3) {
      largest = num2;
    } else {
      largest = num3;
    }

    // Output the largest number
    System.out.println("The largest number is: " + largest);

    scanner.close();
  }
}


3. Write a program to check if a given year is a leap year.

import java.util.Scanner;

public class LeapYearCheck {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the year
    System.out.print("Enter a year: ");
    int year = scanner.nextInt();

    // Check if the year is a leap year
    boolean isLeapYear;

    if (year % 4 == 0) {
      if (year % 100 == 0) {
        if (year % 400 == 0) {
          isLeapYear = true;
        } else {
          isLeapYear = false;
        }
      } else {
        isLeapYear = true;
      }
    } else {
      isLeapYear = false;
    }

    // Output the result
    if (isLeapYear) {
      System.out.println(year + " is a leap year.");
    } else {
      System.out.println(year + " is not a leap year.");
    }

    scanner.close();
  }
}



4. Write a program to calculate the factorial of a number.

import java.util.Scanner;

public class Factorial {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the number
    System.out.print("Enter a number: ");
    int number = scanner.nextInt();

    // Calculate factorial
    long factorial = 1;

    for (int i = 1; i <= number; i++) {
      factorial *= i;
    }

    // Output the result
    System.out.println("The factorial of " + number + " is: " + factorial);

    scanner.close();
  }
}



5. Write a program to generate the Fibonacci series up to a given number.

import java.util.Scanner;

public class FibonacciSeries {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the number up to which the Fibonacci series will be generated
    System.out.print("Enter the number up to which the Fibonacci series should be generated: ");
    int n = scanner.nextInt();

    // Initialize the first two numbers in the Fibonacci series
    int first = 0, second = 1;

    System.out.print("Fibonacci Series up to " + n + ": " + first + ", " + second);

    // Generate the Fibonacci series
    int next;
    while (true) {
      next = first + second;
      if (next > n) {
        break;
      }
      System.out.print(", " + next);
      first = second;
      second = next;
    }

    scanner.close();
  }
}


6. Write a program to reverse a given integer number.

import java.util.Scanner;

public class ReverseInteger {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the number
    System.out.print("Enter an integer number: ");
    int number = scanner.nextInt();

    // Initialize the variable to store the reversed number
    int reversedNumber = 0;

    // Reverse the number
    while (number != 0) {
      int digit = number % 10; // Get the last digit
      reversedNumber = reversedNumber * 10 + digit; // Add the digit to the reversed number
      number = number / 10; // Remove the last digit from the original number
    }

    // Output the reversed number
    System.out.println("Reversed Number: " + reversedNumber);

    scanner.close();
  }
}


7. Write a program to check if a number is a palindrome.

import java.util.Scanner;

public class PalindromeCheck {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the number
    System.out.print("Enter an integer number: ");
    int originalNumber = scanner.nextInt();

    int reversedNumber = 0;
    int temp = originalNumber;

    // Reverse the number
    while (temp != 0) {
      int digit = temp % 10; // Get the last digit
      reversedNumber = reversedNumber * 10 + digit; // Build the reversed number
      temp = temp / 10; // Remove the last digit from temp
    }

    // Check if the original number and reversed number are the same
    if (originalNumber == reversedNumber) {
      System.out.println(originalNumber + " is a palindrome.");
    } else {
      System.out.println(originalNumber + " is not a palindrome.");
    }

    scanner.close();
  }
}


8. Write a program to find the greatest common divisor (GCD) of two numbers.

import java.util.Scanner;

public class GCD {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input two numbers
    System.out.print("Enter the first number: ");
    int num1 = scanner.nextInt();

    System.out.print("Enter the second number: ");
    int num2 = scanner.nextInt();

    // Find GCD using the Euclidean algorithm
    int gcd = findGCD(num1, num2);

    // Output the GCD
    System.out.println("The GCD of " + num1 + " and " + num2 + " is: " + gcd);

    scanner.close();
  }

  // Method to find GCD using Euclidean algorithm
  public static int findGCD(int a, int b) {
    while (b != 0) {
      int temp = b;
      b = a % b;
      a = temp;
    }
    return a;
  }
}


9. Write a program to find the least common multiple (LCM) of two numbers.

import java.util.Scanner;

public class LCM {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input two numbers
    System.out.print("Enter the first number: ");
    int num1 = scanner.nextInt();

    System.out.print("Enter the second number: ");
    int num2 = scanner.nextInt();

    // Calculate LCM
    int lcm = findLCM(num1, num2);

    // Output the LCM
    System.out.println("The LCM of " + num1 + " and " + num2 + " is: " + lcm);

    scanner.close();
  }

  // Method to find LCM using the relationship between GCD and LCM
  public static int findLCM(int a, int b) {
    return (a * b) / findGCD(a, b);
  }

  // Method to find GCD using Euclidean algorithm
  public static int findGCD(int a, int b) {
    while (b != 0) {
      int temp = b;
      b = a % b;
      a = temp;
    }
    return a;
  }
}


10. Write a program to print the prime numbers up to a given number.

import java.util.Scanner;

public class PrimeNumbers {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the number up to which prime numbers will be printed
    System.out.print("Enter a number: ");
    int n = scanner.nextInt();

    System.out.println("Prime numbers up to " + n + " are:");

    // Print prime numbers from 2 to n
    for (int i = 2; i <= n; i++) {
      if (isPrime(i)) {
        System.out.print(i + " ");
      }
    }

    scanner.close();
  }

  // Method to check if a number is prime
  public static boolean isPrime(int num) {
    if (num <= 1) {
      return false;
    }
    for (int i = 2; i <= Math.sqrt(num); i++) {
      if (num % i == 0) {
        return false;
      }
    }
    return true;
  }
}


11. Write a program to check if a number is prime.

import java.util.Scanner;

public class PrimeCheck {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the number to check
    System.out.print("Enter an integer number: ");
    int number = scanner.nextInt();

    // Check if the number is prime
    boolean isPrime = isPrime(number);

    // Output the result
    if (isPrime) {
      System.out.println(number + " is a prime number.");
    } else {
      System.out.println(number + " is not a prime number.");
    }

    scanner.close();
  }

  // Method to check if a number is prime
  public static boolean isPrime(int num) {
    if (num <= 1) {
      return false;
    }
    for (int i = 2; i <= Math.sqrt(num); i++) {
      if (num % i == 0) {
        return false;
      }
    }
    return true;
  }
}


12. Write a program to calculate the sum of digits of a number.

import java.util.Scanner;

public class SumOfDigits {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the number
    System.out.print("Enter an integer number: ");
    int number = scanner.nextInt();

    // Initialize the variable to store the sum of digits
    int sum = 0;

    // Calculate the sum of digits
    while (number != 0) {
      int digit = number % 10; // Get the last digit
      sum += digit; // Add the digit to the sum
      number = number / 10; // Remove the last digit from the number
    }

    // Output the sum of digits
    System.out.println("The sum of the digits is: " + sum);

    scanner.close();
  }
}


13. Write a program to calculate the power of a number using recursion.

import java.util.Scanner;

public class PowerCalculation {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the base and exponent
    System.out.print("Enter the base number: ");
    int base = scanner.nextInt();

    System.out.print("Enter the exponent: ");
    int exponent = scanner.nextInt();

    // Calculate the power using recursion
    long result = power(base, exponent);

    // Output the result
    System.out.println(base + " raised to the power of " + exponent + " is: " + result);

    scanner.close();
  }

  // Recursive method to calculate power
  public static long power(int base, int exponent) {
    if (exponent == 0) { // Base case: any number raised to the power of 0 is 1
      return 1;
    } else if (exponent > 0) { // Recursive case: multiply the base with the result of power(base, exponent - 1)
      return base * power(base, exponent - 1);
    } else { // Handle negative exponents if needed
      return 1 / power(base, -exponent); // Convert the problem to positive exponent for simplicity
    }
  }
}


14. Write a program to swap two numbers without using a third variable.

import java.util.Scanner;

public class SwapNumbers {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the two numbers
    System.out.print("Enter the first number: ");
    int num1 = scanner.nextInt();

    System.out.print("Enter the second number: ");
    int num2 = scanner.nextInt();

    // Print the original numbers
    System.out.println("Before swapping:");
    System.out.println("num1 = " + num1);
    System.out.println("num2 = " + num2);

    // Swap the numbers without using a third variable
    num1 = num1 + num2; // Step 1: Add num1 and num2, store the result in num1
    num2 = num1 - num2; // Step 2: Subtract num2 from num1, store the result in num2
    num1 = num1 - num2; // Step 3: Subtract the new num2 from num1, store the result in num1

    // Print the swapped numbers
    System.out.println("After swapping:");
    System.out.println("num1 = " + num1);
    System.out.println("num2 = " + num2);

    scanner.close();
  }
}


15. Write a program to find the sum of the first N natural numbers.

import java.util.Scanner;

public class SumOfNaturalNumbers {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the number N
    System.out.print("Enter the value of N: ");
    int N = scanner.nextInt();

    // Calculate the sum of the first N natural numbers
    int sum = calculateSum(N);

    // Output the result
    System.out.println("The sum of the first " + N + " natural numbers is: " + sum);

    scanner.close();
  }

  // Method to calculate the sum of the first N natural numbers
  public static int calculateSum(int N) {
    // Using the formula for the sum of the first N natural numbers: sum = N * (N + 1) / 2
    return N * (N + 1) / 2;
  }
}


16. Write a program to check if a number is an Armstrong number.

import java.util.Scanner;

public class ArmstrongNumberCheck {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the number
    System.out.print("Enter an integer number: ");
    int number = scanner.nextInt();

    // Check if the number is an Armstrong number
    boolean isArmstrong = isArmstrongNumber(number);

    // Output the result
    if (isArmstrong) {
      System.out.println(number + " is an Armstrong number.");
    } else {
      System.out.println(number + " is not an Armstrong number.");
    }

    scanner.close();
  }

  // Method to check if a number is an Armstrong number
  public static boolean isArmstrongNumber(int num) {
    int originalNumber = num;
    int numberOfDigits = String.valueOf(num).length();
    int sum = 0;

    // Calculate the sum of each digit raised to the power of the number of digits
    while (num != 0) {
      int digit = num % 10;
      sum += Math.pow(digit, numberOfDigits);
      num /= 10;
    }

    // Check if the sum is equal to the original number
    return sum == originalNumber;
  }
}


17. Write a program to check if a number is a perfect number.

import java.util.Scanner;

public class PerfectNumberCheck {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the number
    System.out.print("Enter an integer number: ");
    int number = scanner.nextInt();

    // Check if the number is a perfect number
    boolean isPerfect = isPerfectNumber(number);

    // Output the result
    if (isPerfect) {
      System.out.println(number + " is a perfect number.");
    } else {
      System.out.println(number + " is not a perfect number.");
    }

    scanner.close();
  }

  // Method to check if a number is a perfect number
  public static boolean isPerfectNumber(int num) {
    if (num <= 1) {
      return false;
    }

    int sum = 0;

    // Find the sum of the proper divisors
    for (int i = 1; i <= num / 2; i++) {
      if (num % i == 0) {
        sum += i;
      }
    }

    // Check if the sum of the proper divisors is equal to the original number
    return sum == num;
  }
}


18. Write a program to find the average of N numbers.

import java.util.Scanner;

public class AverageOfNumbers {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the number of elements
    System.out.print("Enter the number of elements: ");
    int N = scanner.nextInt();

    // Validate input
    if (N <= 0) {
      System.out.println("The number of elements must be greater than zero.");
      scanner.close();
      return;
    }

    // Input the numbers and calculate the sum
    double sum = 0;
    for (int i = 1; i <= N; i++) {
      System.out.print("Enter number " + i + ": ");
      double number = scanner.nextDouble();
      sum += number;
    }

    // Calculate the average
    double average = sum / N;

    // Output the result
    System.out.println("The average of the " + N + " numbers is: " + average);

    scanner.close();
  }
}


19. Write a program to find the second largest number in an array.

import java.util.Scanner;

public class SecondLargestNumber {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the number of elements in the array
    System.out.print("Enter the number of elements in the array: ");
    int n = scanner.nextInt();

    // Validate input
    if (n < 2) {
      System.out.println("Array must have at least two elements.");
      scanner.close();
      return;
    }

    // Initialize the array
    int[] numbers = new int[n];

    // Input the elements of the array
    System.out.println("Enter the elements of the array:");
    for (int i = 0; i < n; i++) {
      numbers[i] = scanner.nextInt();
    }

    // Find the second largest number
    int firstLargest = Integer.MIN_VALUE;
    int secondLargest = Integer.MIN_VALUE;

    for (int num: numbers) {
      if (num > firstLargest) {
        secondLargest = firstLargest;
        firstLargest = num;
      } else if (num > secondLargest && num < firstLargest) {
        secondLargest = num;
      }
    }

    // Output the result
    if (secondLargest == Integer.MIN_VALUE) {
      System.out.println("There is no second largest number.");
    } else {
      System.out.println("The second largest number is: " + secondLargest);
    }

    scanner.close();
  }
}


20. Write a program to find the sum of all prime numbers up to a given number.

import java.util.Scanner;

public class SumOfPrimes {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input the upper limit
    System.out.print("Enter an upper limit: ");
    int upperLimit = scanner.nextInt();

    // Validate input
    if (upperLimit < 2) {
      System.out.println("There are no prime numbers less than 2.");
      scanner.close();
      return;
    }

    // Calculate the sum of prime numbers up to the upper limit
    int sum = 0;
    for (int i = 2; i <= upperLimit; i++) {
      if (isPrime(i)) {
        sum += i;
      }
    }

    // Output the result
    System.out.println("The sum of all prime numbers up to " + upperLimit + " is: " + sum);

    scanner.close();
  }

  // Method to check if a number is prime
  public static boolean isPrime(int num) {
    if (num <= 1) {
      return false;
    }
    if (num == 2) {
      return true; // 2 is the only even prime number
    }
    if (num % 2 == 0) {
      return false; // Exclude all other even numbers
    }
    for (int i = 3; i <= Math.sqrt(num); i += 2) {
      if (num % i == 0) {
        return false;
      }
    }
    return true;
  }
}


Array Problems

  1. Reverse an array:

    public class ReverseArray { public static void reverseArray(int[] arr) { int start = 0, end = arr.length - 1; 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}; reverseArray(arr); for (int i : arr) { System.out.print(i + " "); } } }
  2. Find the maximum and minimum elements in an array:


    public class MaxMinArray { public static void findMaxMin(int[] arr) { int max = arr[0]; int min = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; } System.out.println("Max: " + max + ", Min: " + min); } public static void main(String[] args) { int[] arr = {12, 5, 7, 9, 3}; findMaxMin(arr); } }
  3. Sort an array using bubble sort:

    public class BubbleSort { public static void bubbleSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { 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); for (int i : arr) { System.out.print(i + " "); } } }
  4. Sort an array using insertion sort:


    public class InsertionSort { public static void insertionSort(int[] arr) { for (int i = 1; i < arr.length; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } } public static void main(String[] args) { int[] arr = {12, 11, 13, 5, 6}; insertionSort(arr); for (int i : arr) { System.out.print(i + " "); } } }
  5. Find the missing number in an array:


    public class MissingNumber { public static int findMissingNumber(int[] arr) { int n = arr.length + 1; int total = n * (n + 1) / 2; int sum = 0; for (int num : arr) { sum += num; } return total - sum; } public static void main(String[] args) { int[] arr = {1, 2, 3, 5}; System.out.println("Missing number: " + findMissingNumber(arr)); } }
  6. Remove duplicates from an array:


    import java.util.HashSet; public class RemoveDuplicates { public static void removeDuplicates(int[] arr) { HashSet<Integer> set = new HashSet<>(); for (int num : arr) { set.add(num); } System.out.println(set); } public static void main(String[] args) { int[] arr = {1, 2, 3, 1, 2, 4, 5}; removeDuplicates(arr); } }
  7. Find common elements between two arrays:


    import java.util.HashSet; public class CommonElements { public static void findCommonElements(int[] arr1, int[] arr2) { HashSet<Integer> set1 = new HashSet<>(); for (int num : arr1) { set1.add(num); } for (int num : arr2) { if (set1.contains(num)) { System.out.print(num + " "); } } } public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4}; int[] arr2 = {3, 4, 5, 6}; findCommonElements(arr1, arr2); } }
  8. Merge two sorted arrays:


    public class MergeSortedArrays { public static int[] mergeArrays(int[] arr1, int[] arr2) { int[] result = new int[arr1.length + arr2.length]; int i = 0, j = 0, k = 0; while (i < arr1.length && j < arr2.length) { if (arr1[i] < arr2[j]) { result[k++] = arr1[i++]; } else { result[k++] = arr2[j++]; } } while (i < arr1.length) { result[k++] = arr1[i++]; } while (j < arr2.length) { result[k++] = arr2[j++]; } return result; } public static void main(String[] args) { int[] arr1 = {1, 3, 5}; int[] arr2 = {2, 4, 6}; int[] merged = mergeArrays(arr1, arr2); for (int num : merged) { System.out.print(num + " "); } } }
  9. Rotate an array by K positions:


    public class RotateArray { public static void rotateArray(int[] arr, int k) { k = k % arr.length; // In case k is larger than array length reverse(arr, 0, arr.length - 1); reverse(arr, 0, k - 1); reverse(arr, k, arr.length - 1); } private 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; rotateArray(arr, k); for (int num : arr) { System.out.print(num + " "); } } }
  10. Find the frequency of each element in an array:


    import java.util.HashMap; public class ElementFrequency { public static void findFrequency(int[] arr) { HashMap<Integer, Integer> map = new HashMap<>(); for (int num : arr) { map.put(num, map.getOrDefault(num, 0) + 1); } System.out.println(map); } public static void main(String[] args) { int[] arr = {1, 2, 2, 3, 3, 3}; findFrequency(arr); } }

String Problems

  1. Check if a string is a palindrome:


    public class Palindrome { public static boolean isPalindrome(String str) { int start = 0, end = str.length() - 1; while (start < end) { if (str.charAt(start) != str.charAt(end)) { return false; } start++; end--; } return true; } public static void main(String[] args) { String str = "madam"; System.out.println(isPalindrome(str)); } }
  2. Count vowels and consonants in a string:

    public class VowelConsonantCount { public static void countVowelsAndConsonants(String str) { int vowels = 0, consonants = 0; for (char c : str.toLowerCase().toCharArray()) { if (Character.isLetter(c)) { if ("aeiou".indexOf(c) != -1) { vowels++; } else { consonants++; } } } System.out.println("Vowels: " + vowels + ", Consonants: " + consonants); } public static void main(String[] args) { String str = "Hello World"; countVowelsAndConsonants(str); } }
  3. Reverse a string:


    public class ReverseString { public static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } public static void main(String[] args) { String str = "Hello"; System.out.println(reverseString(str)); } }
  4. Find the first non-repeated character in a string:


    public class FirstNonRepeatedChar { public static char firstNonRepeated(String str) { for (int i = 0; i < str.length(); i++) { if (str.indexOf(str.charAt(i)) == str.lastIndexOf(str.charAt(i))) { return str.charAt(i); } } return '\0'; // Return null character if no non-repeated character is found } public static void main(String[] args) { String str = "swiss"; System.out.println(firstNonRepeated(str)); } }
  5. Check if two strings are anagrams:


    import java.util.Arrays; public class Anagram { 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(areAnagrams(str1, str2)); } }
  6. Find all permutations of a given string:


    import java.util.*; public class Permutations { public static void permute(String str, int left, int right, List<String> result) { if (left == right) { result.add(str); } else { for (int i = left; i <= right; i++) { str = swap(str, left, i); permute(str, left + 1, right, result); str = swap(str, left, i); // Backtrack } } } public static String swap(String str, int i, int j) { char[] charArray = str.toCharArray(); char temp = charArray[i]; charArray[i] = charArray[j]; charArray[j] = temp; return new String(charArray); } public static void main(String[] args) { String str = "ABC"; List<String> result = new ArrayList<>(); permute(str, 0, str.length() - 1, result); System.out.println(result); } }
  7. Remove all white spaces from a string:

    public class RemoveWhitespace { public static String removeWhitespace(String str) { return str.replaceAll("\\s+", ""); } public static void main(String[] args) { String str = "Hello World"; System.out.println(removeWhitespace(str)); } }
  8. Check if a string contains only digits:


    public class CheckDigits { public static boolean isDigits(String str) { return str.matches("[0-9]+"); } public static void main(String[] args) { String str = "12345"; System.out.println(isDigits(str)); } }
  9. Find the longest substring without repeating characters:


    public class LongestSubstring { public static int longestSubstring(String str) { int n = str.length(); int maxLength = 0; Set<Character> set = new HashSet<>(); int start = 0; for (int end = 0; end < n; end++) { while (set.contains(str.charAt(end))) { set.remove(str.charAt(start)); start++; } set.add(str.charAt(end)); maxLength = Math.max(maxLength, end - start + 1); } return maxLength; } public static void main(String[] args) { String str = "abcabcbb"; System.out.println(longestSubstring(str)); } }
  10. Count the occurrence of each character in a string:


    import java.util.HashMap; public class CharFrequency { public static void countFrequency(String str) { HashMap<Character, Integer> map = new HashMap<>(); for (char c : str.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } System.out.println(map); } public static void main(String[] args) { String str = "hello"; countFrequency(str); } }

Searching and Sorting Algorithms

  1. Binary search:

    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; // Not found } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int target = 3; System.out.println(binarySearch(arr, target)); } }
  2. Linear search:


    public class LinearSearch { public static int linearSearch(int[] arr, int target) { for (int i = 0; i < arr.length; i++) { if (arr[i] == target) return i; } return -1; // Not found } public static void main(String[] args) { int[] arr = {10, 20, 30, 40, 50}; int target = 30; System.out.println(linearSearch(arr, target)); } }
  3. Selection sort:

    public class SelectionSort { public static void selectionSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { int minIndex = i; for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } int temp = arr[minIndex]; arr[minIndex] = arr[i]; arr[i] = temp; } } public static void main(String[] args) { int[] arr = {64, 34, 25, 12, 22, 11, 90}; selectionSort(arr); for (int i : arr) { System.out.print(i + " "); } } } 
     
     
     
     
     
    1. Merge Sort:

      public class MergeSort { public static void mergeSort(int[] arr) { if (arr.length < 2) return; int mid = arr.length / 2; int[] left = new int[mid]; int[] right = new int[arr.length - mid]; System.arraycopy(arr, 0, left, 0, mid); System.arraycopy(arr, mid, right, 0, arr.length - mid); mergeSort(left); mergeSort(right); merge(arr, left, right); } private static void merge(int[] arr, int[] left, int[] right) { int i = 0, j = 0, k = 0; while (i < left.length && j < right.length) { if (left[i] <= right[j]) { arr[k++] = left[i++]; } else { arr[k++] = right[j++]; } } while (i < left.length) arr[k++] = left[i++]; while (j < right.length) arr[k++] = right[j++]; } public static void main(String[] args) { int[] arr = {38, 27, 43, 3, 9, 82, 10}; mergeSort(arr); for (int num : arr) { System.out.print(num + " "); } } }
    2. Quick Sort:


      public class QuickSort { public static void quickSort(int[] arr, int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } private static int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j < high; j++) { if (arr[j] <= pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } public static void main(String[] args) { int[] arr = {10, 80, 30, 90, 40, 50, 70}; quickSort(arr, 0, arr.length - 1); for (int num : arr) { System.out.print(num + " "); } } }
    3. Heap Sort:

      public class HeapSort { public static void heapSort(int[] arr) { int n = arr.length; for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); } for (int i = n - 1; i >= 0; i--) { int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapify(arr, i, 0); } } private static void heapify(int[] arr, int n, int i) { int largest = i; int left = 2 * i + 1; int right = 2 * i + 2; if (left < n && arr[left] > arr[largest]) { largest = left; } if (right < n && arr[right] > arr[largest]) { largest = right; } if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; heapify(arr, n, largest); } } public static void main(String[] args) { int[] arr = {4, 10, 3, 5, 1}; heapSort(arr); for (int num : arr) { System.out.print(num + " "); } } }
    4. Find the kth smallest/largest element in an array:

      import java.util.Arrays; public class KthSmallest { public static int findKthSmallest(int[] arr, int k) { Arrays.sort(arr); return arr[k - 1]; } public static int findKthLargest(int[] arr, int k) { Arrays.sort(arr); return arr[arr.length - k]; } public static void main(String[] args) { int[] arr = {12, 3, 5, 7, 19}; int k = 2; System.out.println("Kth smallest: " + findKthSmallest(arr, k)); System.out.println("Kth largest: " + findKthLargest(arr, k)); } }
    5. Search an element in a rotated sorted array:


      public class RotatedBinarySearch { public static int search(int[] arr, int target) { int low = 0, high = arr.length - 1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) return mid; if (arr[low] <= arr[mid]) { if (arr[low] <= target && target < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } else { if (arr[mid] < target && target <= arr[high]) { low = mid + 1; } else { high = mid - 1; } } } return -1; // Not found } public static void main(String[] args) { int[] arr = {6, 7, 9, 15, 19, 2, 3}; int target = 3; System.out.println(search(arr, target)); } }
    6. Dutch National Flag Problem (Sort 0s, 1s, and 2s):

      public class DutchNationalFlag { public static void sortColors(int[] arr) { int low = 0, mid = 0, high = arr.length - 1; while (mid <= high) { switch (arr[mid]) { case 0: swap(arr, low++, mid++); break; case 1: mid++; break; case 2: swap(arr, mid, high--); break; } } } private static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void main(String[] args) { int[] arr = {2, 0, 1, 2, 0, 1, 1}; sortColors(arr); for (int num : arr) { System.out.print(num + " "); } } }
    7. Find the intersection of two sorted arrays:


      public class IntersectionSortedArrays { public static void findIntersection(int[] arr1, int[] arr2) { int i = 0, j = 0; while (i < arr1.length && j < arr2.length) { if (arr1[i] == arr2[j]) { System.out.print(arr1[i] + " "); i++; j++; } else if (arr1[i] < arr2[j]) { i++; } else { j++; } } } public static void main(String[] args) { int[] arr1 = {1, 3, 4, 5, 7}; int[] arr2 = {2, 3, 5, 6}; findIntersection(arr1, arr2); } }

    Mathematical and Number-Based Problems

    1. Check if a number is a power of two:

      public class PowerOfTwo { public static boolean isPowerOfTwo(int num) { return num > 0 && (num & (num - 1)) == 0; } public static void main(String[] args) { int num = 16; System.out.println(isPowerOfTwo(num)); } }
    2. Find the square root of a number without using a built-in function:

      public class SquareRoot { public static int sqrt(int num) { int left = 0, right = num; while (left <= right) { int mid = left + (right - left) / 2; if (mid * mid == num) { return mid; } else if (mid * mid < num) { left = mid + 1; } else { right = mid - 1; } } return right; // Return floor of the square root } public static void main(String[] args) { int num = 10; System.out.println(sqrt(num)); } }
    3. Find the nth Fibonacci number using dynamic programming:

      public class Fibonacci { 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) { int n = 9; System.out.println(fibonacci(n)); } }
    4. Generate all prime numbers less than N using the Sieve of Eratosthenes:

      public class SieveOfEratosthenes { public static void sieve(int n) { boolean[] primes = new boolean[n + 1]; for (int i = 2; i <= n; i++) { primes[i] = true; } for (int i = 2; i * i <= n; i++) { if (primes[i]) { for (int j = i * i; j <= n; j += i) { primes[j] = false; } } } for (int i = 2; i <= n; i++) { if (primes[i]) { System.out.print(i + " "); } } } public static void main(String[] args) { int n = 50; sieve(n); } }
    5. Calculate the binomial coefficient:


      public class BinomialCoefficient { public static int binomialCoefficient(int n, int k) { int[][] dp = new int[n + 1][k + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.min(i, k); j++) { if (j == 0 || j == i) { dp[i][j] = 1; } else { dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]; } } } return dp[n][k]; } public static void main(String[] args) { int n = 5, k = 2; System.out.println(binomialCoefficient(n, k)); } }
     

Contact Form

Name

Email *

Message *