***************coding Interview Questions Programs***************
=====================================================================
package com.InterviewPrep;
import java.util.Arrays;
public class AnagramCheckerWithStreamapi {
public static void main(String[] args) {
String str1 = "Listen";
String str2 = "silent";
boolean isAnagram =Arrays.equals(str1.toLowerCase()
.chars().sorted().toArray(), str2.toLowerCase()
.chars().sorted().toArray());
System.out.println(isAnagram ? "Anagrams" : "Not Anagrams");
}
}
=========================
package com.InterviewPrep;
import java.util.Arrays;
public class AnagramCheckEx2 {
public static void main(String[] args) {
String str1 = "Listen";
String str2 = "silent";
// Convert strings to char arrays and sort them
char[] arr1 = str1.toLowerCase().toCharArray();
char[] arr2 = str2.toLowerCase().toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
// Compare the sorted arrays
if (Arrays.equals(arr1, arr2)) {
System.out.println(str1 + " and " + str2 + " are anagrams.");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams.");
}
}
}
===================================
package com.InterviewPrep;
public class Armstrong {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a valid input.");
return;
}
int num = Integer.parseInt(args[0]);
int sum = 0, temp = num, digits = Integer.toString(num).length();
while (temp > 0) {
sum += Math.pow(temp % 10, digits);
temp /= 10;
}
System.out.println(sum == num ? num + " is Armstrong" : num + " is not
Armstrong");
}
}
================================
package com.InterviewPrep;
import java.util.Arrays;
public class ArrayEqualityChecker {
public static void main(String[] args) {
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {1, 2, 3, 4, 5};
int[] array3 = {1, 2, 3, 4, 6};
// Check if two arrays are equal
boolean result1 = Arrays.equals(array1, array2); // Should return true
boolean result2 = Arrays.equals(array1, array3); // Should return false
System.out.println("array1 and array2 are equal: " + result1);
System.out.println("array1 and array3 are equal: " + result2);
}
}
================================
package com.InterviewPrep;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CharacterCountWithStreams {
public static void main(String[] args) {
String str1 = "abcdABCDabcd";
Map<Character, Long> charsCount = str1.chars()
.mapToObj(c -> (char) c) // Convert int stream to Character stream
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting())); // Count each character
System.out.println(charsCount); // Output: {a=2, A=1, b=2, B=1, c=2, C=1,
d=2, D=1}
}
}
============================
package com.InterviewPrep;
public class CharacterPyramid {
public static void main(String[] args) {
char ch = 'A'; // Starting character
int rows = 5; // Number of rows
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" "); // Print spaces
}
for (int k = 1; k <= (2 * i - 1); k++) {
System.out.print(ch); // Print the character
}
System.out.println();
ch++; // Move to the next character
}
}
}
===================================
package com.InterviewPrep;
public class CheckOnlyDigitsInString {
public static void main(String[] args) {
String input = "123456"; // Example string
// Check if the string contains only digits using regex
if (input.matches("[0-9]+")) {
System.out.println("The string contains only digits.");
} else {
System.out.println("The string does not contain only digits.");
}
}
}
=======================================
package com.InterviewPrep;
import java.util.ArrayList;
import java.util.List;
public class Count_OddandEven_Numbers {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6};
int evencount = 0;
int oddcount = 0;
List<Integer> evenNumbers = new ArrayList<>();
List<Integer> oddNumbers = new ArrayList<>();
for (int bs : a) {
if (bs % 2 == 0) { // Correct condition
evencount++;
evenNumbers.add(bs);
} else {
oddcount++;
oddNumbers.add(bs);
}
}
// Final counts and numbers
System.out.println("Total even numbers: " + evencount);
System.out.println("Even numbers: " + evenNumbers);
System.out.println("Total odd numbers: " + oddcount);
System.out.println("Odd numbers: " + oddNumbers);
}
}
=====================================
package com.InterviewPrep;
import java.util.Arrays;
public class countingOddNumbers {
public static void main(String[] args) {
int [] array = {1,2,3,4,5,6,7,8,9,10};
// for(int num : array){
// if(num%2 !=0){
// System.out.println("odd numbers are :"+ num);
// }
// }
// using streamapi
// Arrays.stream(array).filter(num->num%2!=0).forEach(num->
System.out.println("odd num is "+num));
//using count method
long count = Arrays.stream(array)
.filter(num->num%2!=0)
.peek(num-> System.out.println("odd num is "+num))
.count();
System.out.println("total number os odd numbers is :"+ count);
}
}
=======================================
package com.InterviewPrep;
public class CountSpecificLetterInString {
public static void main(String[] args) {
String s = "india is a country";
// Using Java 8 Streams to count occurrences of 'i'
long countno = s.chars() // Convert string to IntStream
.filter(c -> c == 'i') // Filter the characters where 'i' is
present
.count(); // Count the occurrences
System.out.println("Number of occurrences of 'i': " + countno);
}
}
=====================================
package com.InterviewPrep;
public class CountSumofDigits {
public static void main(String[] args) {
int n = 01234567;
int sum = 0;
while(n>0){
sum += n%10;
n = n/10;
sum++;
}
System.out.println("Total digits sum is : "+sum);
}
}
===================================
package com.InterviewPrep;
public class CountTotalDigits {
public static void main(String[] args) {
int n = 123455679;
int count = 0;
while(n>0){
n = n/10;
count++;
}
System.out.println("total digits in number are : "+count);
}
}
====================================
package com.InterviewPrep;
public class DuckNumber {
public static void main(String[] args) {
int num = 101;
System.out.println(num + " is " + (isDuckNumber(num) ? "a Duck number" :
"not a Duck number"));
}
public static boolean isDuckNumber(int num) {
String numStr = String.valueOf(num);
return numStr.charAt(0) != '0' && numStr.contains("0");
}
}
======================
package com.InterviewPrep;
import java.util.HashMap;
import java.util.Map;
public class DuplicateElimentinArray {
public static void main(String[] args) {
//approach 1
String [] arr = {"java","c++","python","java","mongodb"};
// HashSet<String> hs = new HashSet<>();
// for(String a : arr){
// if(hs.add(a)== false){
// System.out.println("Duplicate eliment is :"+ a);
// }
//
// }
//approach 2
HashMap<String,Integer> hs = new HashMap<>();
for(String b : arr){
hs.put(b,hs.getOrDefault(b,0)+1);
}
for(Map.Entry<String,Integer> entry : hs.entrySet()){
if(entry.getValue()>1){
System.out.println("duplicate key is :"+ entry.getKey());
}
}
}
}
===========================================
package com.InterviewPrep;
import java.util.*;
import java.util.stream.Collectors;
public class DuplicateLettersRemove {
public static void main(String[] args) {
String[] s = {"Bananas", "Apple", "tomato"};
for (String word : s) {
// Using LinkedHashSet to preserve order and remove duplicates
String result = new LinkedHashSet<>(Arrays.asList(word.split("")))
.stream()
.collect(Collectors.joining());
System.out.println(result);
}
}
}
===================================
package com.InterviewPrep;
import com.naresh.Employees;
import java.util.ArrayList;
import java.util.Comparator;
public class EmployeesSortedDescendingbyName {
public static void main(String[] args) {
ArrayList<Employees> emplist = new ArrayList<>();
emplist.add(new Employees("Naresh",1,"Development",30000));
emplist.add(new Employees("Rajesh",2,"Safety",28000));
emplist.add(new Employees("Karna",3,"Development",31000));
emplist.add(new Employees("Fiona",4,"Testing",28000));
//Descending order
// emplist.sort((e1,e2)->e2.getName().compareTo(e1.getName()));
// for Ascending oreder
// emplist.sort((e1,e2)->e1.getName().compareTo(e2.getName()));
// Define a Comparator for natural sorting by name
// Comparator<Employees> nameComparator =
Comparator.comparing(Employees::getName);
// Define a Comparator for customized sorting or Descending order by name
Comparator<Employees> nameComparatorDesc =
Comparator.comparing(Employees::getName).reversed();
// Sort the list using the Comparator
emplist.sort(nameComparatorDesc);
// emplist.forEach(System.out::println);
// Skip the first 2 names and print the 3rd one
emplist.stream()
.skip(2) // Skip the first 2 names
.findFirst() // Get the 3rd name (after skipping 2)
.ifPresent(System.out::println); // Print the 3rd name
}
}
=====================================
package com.InterviewPrep;
import java.util.ArrayList;
import java.util.List;
public class ExtractSpacesFromCharArrayExample {
public static void main(String[] args) {
char[] a = {'a', ' ', 'b', ' ', 'c', ' '};
// Create separate lists for spaces and non-spaces
List<Character> nonSpaces = new ArrayList<>();
List<Character> spaces = new ArrayList<>();
// Loop through the char array and add characters to the respective lists
for (char ch : a) {
if (ch == ' ') {
spaces.add(ch); // Add spaces to the spaces list
} else {
nonSpaces.add(ch); // Add non-space characters to nonSpaces list
}
}
List<Character> result = new ArrayList<>(spaces); // Create a new list with
Spaces
result.addAll(nonSpaces); // Add Nonspaces to the list
// Print the concatenated result
System.out.println(result);
}
}
=============================================
package com.InterviewPrep;
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class ExtractZerosFromarray {
public static void main(String[] args) {
int [] a = {1,3,0,4,3,0,0,7};
//concating zeros first and numbers
int [] x = IntStream.concat(
Arrays.stream(a).filter(n->n==0),
Arrays.stream(a).filter(n->n!=0)).toArray();
System.out.println(Arrays.toString(x));
}
}
====================================
package com.InterviewPrep;
import java.util.Arrays;
import java.util.stream.IntStream;
public class ExtractZerosFromArrayEx2 {
public static void main(String[] args) {
int[] a = {1, 3, 0, 4, 3, 0, 0, 7};
// Extracting zeros
int[] zeros = Arrays.stream(a).filter(n -> n == 0).toArray();
// Extracting non-zero numbers
int[] nonZeros = Arrays.stream(a).filter(n -> n != 0).toArray();
// Print extracted zeros and remaining numbers separately
System.out.println("Extracted zeros: " + Arrays.toString(zeros));
System.out.println("Remaining numbers: " + Arrays.toString(nonZeros));
}
}
=====================================
package com.InterviewPrep;
import java.util.Arrays;
import java.util.stream.Stream;
public class ExtractZerosFromStringArray {
public static void main(String[] args) {
String[] a = {"apple", "", "banana", "", "orange", ""};
// Concatenate empty strings first, then the rest of the strings
String[] result = Stream.concat(
Arrays.stream(a).filter(s -> s.isEmpty()), // filter empty strings
Arrays.stream(a).filter(s -> !s.isEmpty())) // filter non-empty
strings
.toArray(String[]::new); // Convert to array
System.out.println(Arrays.toString(result));
}
}
=================================
package com.InterviewPrep;
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please provide number to generate Fibonacci series");
int n = sc.nextInt();
int first = 0, second =1;
System.out.println("fibonacci series : ");
for(int i = 0;i <n;i++){
System.out.println(first+" ");
int next = first+second;
first = second;
second = next;
}
}
}
====================================
package com.InterviewPrep;
import java.util.HashMap;
import java.util.Map;
public class FindFrequencyExample {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a string as input.");
return;
}
// Input string
String str = String.join(" ", args).toLowerCase();
// Create a HashMap to store character frequencies
Map<Character, Integer> freqMap = new HashMap<>();
// Iterate through the string
for (char ch : str.toCharArray()) {
if (ch != ' ') { // Ignore spaces
freqMap.put(ch, freqMap.getOrDefault(ch, 0) + 1);
}
}
// Print the character frequencies in the desired format
freqMap.forEach((key, value) -> System.out.print(key + "" + value + " "));
}
}
=================================
package com.InterviewPrep;
import java.util.Arrays;
import java.util.Collections;
public class FindLargestAndSmallestNumbers {
public static void main(String[] args) {
int [] a = {2,3,5,67,98,123,-5555};
var small = Arrays.stream(a).min().getAsInt();
var large = Arrays.stream(a).max().getAsInt();
System.out.printf("min and max numbers are %d & %d%n ",small,large);
}
}
=====================================
package com.InterviewPrep;
public class FindMissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 4,5, 6,7};
int sum1 = 0;
for(int b : arr){
sum1 = sum1+b;
}
// for (int i = 0; i < arr.length; i++) {
// sum1 = sum1 + arr[i];
// }
System.out.println("sum of elements in array:" + sum1);
int sum2 =0;
for(int j=1; j<=7; j++){
sum2 = sum2+j;
}
System.out.println("sum of elements in array2 :"+sum2);
// int missingnum = sum2-sum1;
System.out.println("missing number is "+ (sum2-sum1));
}
}
=====================================
package com.InterviewPrep;
import java.util.HashMap;
import java.util.Map;
public class FindNonRepeatingThirdCharacterExample {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a string as input.");
return;
}
// Input string
// String str = String.join(" ", args).toLowerCase();
String str = args[0];
// Create a HashMap to store character frequencies
Map<Character, Integer> freqMap = new HashMap<>();
// Populate the frequency map
for (char ch : str.toCharArray()) {
if (ch != ' ') { // Ignore spaces
freqMap.put(ch, freqMap.getOrDefault(ch, 0) + 1);
}
}
// Find the 3rd non-repeating character
int count = 0;
for (char ch : str.toCharArray()) {
if (ch != ' ' && freqMap.get(ch) == 1) { // Check if the character is
non-repeating
count++;
if (count == 3) {
System.out.println("The 3rd non-repeating character is: " +
ch);
return;
}
}
}
System.out.println("There is no 3rd non-repeating character in the input
string.");
}
}
=============================
package com.InterviewPrep;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class GetAnameFromList {
public static void main(String[] args) {
List<String> l = new
ArrayList<>(Arrays.asList("Sam","Ram","Karan","Naresh","Giri","Raja","Kumar","Ashok
","Newton"));
List<String> result = l.stream().filter(n-
>n.startsWith("A")).collect(Collectors.toList());
System.out.println(result);
/**
* Count a in the collection
*/
Long count = l.stream().filter(n->n.contains("N")).count();
System.out.println(count);
}
}
=================================
package com.InterviewPrep;
import java.util.*;
import java.util.stream.Collectors;
public class GetValuesOnlyFromMap {
public static void main(String[] args) {
Map<Integer, String> ma = new HashMap<>();
ma.put(1, "Naresh");
ma.put(2, "Mahesh");
ma.put(3, "Krishna");
ma.put(4, "AdinathGiri");
ma.put(5, "Ashok");
ma.put(6, "Surya");
// approach-1
// Collection<String> cl = ma.values();
// System.out.println(cl);
// Using stream() and collecting the values
// List<String> values = ma.values().stream().collect(Collectors.toList());
// System.out.println(values);
//normal approach
for(Map.Entry<Integer,String> mdta : ma.entrySet() ){
var value = mdta.getValue();
System.out.println(value);
}
}
}
=============================
package com.InterviewPrep;// Java Code to check if two Strings are anagrams of
// each other using sorting
import java.util.Arrays;
class GfG {
// Function to check if two strings are anagrams
static boolean areAnagrams(String s1, String s2) {
// Sort both strings
char[] s1Array = s1.toCharArray();
char[] s2Array = s2.toCharArray();
Arrays.sort(s1Array);
Arrays.sort(s2Array);
// Compare sorted strings
return Arrays.equals(s1Array, s2Array);
}
public static void main(String[] args) {
String s1 = "geeks";
String s2 = "kseeg";
System.out.println(areAnagrams(s1, s2));
}
}
===================================
package com.InterviewPrep;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Groupbydept {
public static ArrayList<Employee> employeedata() {
ArrayList<Employee> ee = new ArrayList<>();
ee.add(new Employee(1, "HR", 12000));
ee.add(new Employee(2, "SALES", 10000));
ee.add(new Employee(3, "ACCOUNTS", 10000));
ee.add(new Employee(4, "QC", 12500));
ee.add(new Employee(5, "SAFETY", 8000));
return ee;
}
public static void main(String[] args) {
var employeedata = employeedata();
System.out.println("Employee Data: " + employeedata);
var collect =
employeedata.stream().collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.groupingBy(Employee::getSalary)));
collect.forEach((department, salaryMap) -> {
System.out.println("Department: " + department);
salaryMap.forEach((salary, employees) -> {
System.out.println(" Salary: " + salary);
employees.forEach(System.out::println);
});
});
}
}
======================================
package com.InterviewPrep;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ListIterator;
public class HalfLinkedListReverseWithInteger {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.add(1);
list.add(10);
list.add(100);
list.add(1000);
list.add(20);
list.add(21);
list.add(1,34);
System.out.println(list);
// Calculate the midpoint
int midpoint = list.size()/2;
// Create a ListIterator starting from the midpoint
ListIterator<Integer> iterator = list.listIterator(midpoint);
// Iterate in reverse order for the first half
for (int i = 0; i < midpoint; i++) {
if (iterator.hasPrevious()) {
System.out.println(iterator.previous());
}
}
Integer [] sechalf = new Integer[list.size() - midpoint];
// Iterate in reverse order for the second half (after the midpoint)
// First, find the midpoint for the second half, then reverse iterate
int index =0;
for (int i = list.size() - 1; i >= midpoint; i--) {
sechalf[index] = list.get(i); // Store the element in the array
index++;
}
System.out.println("Second half in reverse: " + Arrays.toString(sechalf));
}
}
====================================
package com.InterviewPrep;
import java.util.*;
public class HalfLinkedListReverseWithString {
public static void main(String[] args) {
// Creating and populating the LinkedList
LinkedList<String> list = new LinkedList<>();
list.add("Naresh");
list.add("Narasimha");
list.add("Frances");
list.add("John");
list.add("Suman");
list.add("Dinesh");
list.add("Raja");
System.out.println("Original Linked List: " + list);
// Find the midpoint of the list
int midpoint = list.size() / 2;
// First half of the list (to be reversed)
List<String> firstHalf = new ArrayList<>(list.subList(0, midpoint));
Collections.reverse(firstHalf);
// Second half of the list (to be reversed)
List<String> secondHalf = new ArrayList<>(list.subList(midpoint,
list.size()));
Collections.reverse(secondHalf);
// Print the reversed first half and second half
System.out.println("Reversed first half of Linked List: " + firstHalf);
System.out.println("Reversed second half of Linked List: " + secondHalf);
}
}
===================================
package com.InterviewPrep;
import java.time.Year;
public class Leapyearchecker {
public static void main(String[] args) {
var i = Integer.parseInt(args[0]);
Year y = Year.of(i);
if(y.isLeap()){
System.out.println(y+" is leap year");
}
else {
System.out.println(y + " not a leap year");
}
}
}
===================================
package com.InterviewPrep;
import java.util.*;
public class MaxNumberFind {
public static void main(String[] args) {
// Create a list of integers
List<Integer> l = Arrays.asList(12, 34, 56, 6, 9, 45, 2344, 90, 45);
// Use Collections.max() to find the maximum number
int max = Collections.max(l);
// Print the maximum number
System.out.println("Max Number: " + max);
}
}
====================================
package com.InterviewPrep;
import java.util.Scanner;
public class MaxNumberFindByTakingValuesFromScanner {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read the size of the array
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
// Create an array of the given size
int[] numbers = new int[size];
// Read array elements from the user
System.out.println("Enter the numbers:");
for (int i = 0; i < size; i++) {
numbers[i] = scanner.nextInt();
}
// Find the maximum number manually
int max = numbers[0]; // Start by assuming the first element is the maximum
for (int num : numbers) {
if (num > max) {
max = num;
}
}
// Print the maximum number
System.out.println("Max Number: " + max);
scanner.close();
}
}
========================================
package com.InterviewPrep;
import java.util.*;
public class MaxNumberFindWithOutCollectionsMax {
public static void main(String[] args) {
// Create a list of integers
List<Integer> l = Arrays.asList(12, 34, 56, 6, 9, 45, 2348, 9000, 45);
// Initialize max with the first element
int max = l.get(0);
// Iterate through the list to find the maximum number
for (int num : l) {
if (num > max) {
max = num;
}
}
// Print the maximum number
System.out.println("Max Number: " + max);
}
}
====================================
package com.InterviewPrep;
import java.util.Arrays;
public class MaxTwoFinder {
public static void main(String[] args) {
int[] v = {3, 546, 66, 774, 2, 1, 0};
// Sort the array in ascending order
Arrays.sort(v);
// Print the largest and second largest numbers (after sorting, they will
be the last two elements)
int max1 = v[v.length - 1]; // Largest number
int max2 = v[v.length - 2]; // Second largest number
System.out.println("The two largest numbers are: " + max1 + " and " +
max2);
}
}
=============================
package com.InterviewPrep;
import java.util.*;
public class MaxTwoNumbersUsingCollectionsReverse {
public static void main(String[] args) {
// Create a list of integers
List<Integer> numbers = Arrays.asList(12, 34, 56, 6, 9, 45, 24, 90, 45);
// Sort the list in descending order
numbers.sort(Collections.reverseOrder());
// Get the two largest numbers
int max1 = numbers.get(0);
int max2 = numbers.get(1);
// Print the two largest numbers
System.out.printf("The two largest numbers are %d and %d%n", max1, max2);
}
}
=======================================
package com.InterviewPrep;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class MergeTwoLists {
public static void main(String[] args) {
List<Integer> l1 = new ArrayList<>();
l1.add(1);
l1.add(2);
l1.add(3);
List<Integer> l2 = new ArrayList<>();
l2.add(4);
l2.add(5);
l2.add(6);
//approach -1
// List<Integer> l3 = new ArrayList<>(l1);
// l3.addAll(l2);
// System.out.println(l3);
// Use flatMap by converting each list into a stream and then flattening
them
Stream.of(l1, l2)
.flatMap(List::stream) // Flatten both lists into a single stream
.forEach(System.out::println); // Print each element
}
}
============================================
package com.InterviewPrep;
import java.util.*;
public class MiddleWordChecker {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please provide the input string or Number:");
String input = sc.nextLine();
System.out.println("Please provide the input to find:");
String wordtofind = sc.nextLine();
// Check if the word is larger than the input
if (wordtofind.length() > input.length()) {
System.out.println("The input to find is larger than the input.");
return;
}
// Calculate the starting index of the middle substring
int midstart = (input.length() - wordtofind.length()) / 2;
// Check if the word is present in the middle
if (input.substring(midstart, midstart +
wordtofind.length()).equals(wordtofind)) {
System.out.println("The input to find is present in the middle of the
input: " + wordtofind);
} else {
System.out.println("The input to find is not present in the middle of
the input: " + wordtofind);
}
}
}
======================================
package com.InterviewPrep;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MultipleByFiveUsingStreams {
public static void main(String[] args) {
int c = Integer.parseInt(args[0]);
List<Integer> al = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<Integer> result = al.stream().map(n-
>n*c).collect(Collectors.toList());
System.out.println(result);
}
}
==========================================
package com.InterviewPrep;
//import java.util.stream.*;
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
boolean isPalindrome = str.equals(
new StringBuilder(str).reverse().toString());
System.out.println(isPalindrome ? "Palindrome" : "Not Palindrome");
}
}
========================================
package com.InterviewPrep;
import java.util.Scanner;
public class PalindromeStringCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter input to check palindrome");
String input = sc.nextLine();
int inputlength = input.length();
String rev = "";
for(int i = inputlength-1;i>=0;i--){
rev += input.charAt(i);
}
if(input.toLowerCase().equals(rev.toLowerCase())){
System.out.println("given input is palindrome "+ input);
}
else{
System.out.println("given input is not palindrome "+ input);
}
}
}
===================================
package com.InterviewPrep;
public class PrimeChecker {
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
if (num > 1 && isPrime(num)) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
public static boolean isPrime(int num) {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}
}
==================================
package com.InterviewPrep;
import java.util.stream.IntStream;
public class PrimeCheckerWithStreams {
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
// Check if the number is prime using IntStream and a lambda expression
System.out.println(num + (num > 1 && IntStream.range(2, (int)
Math.sqrt(num) + 1)
.noneMatch(i -> num % i == 0) ? " is a prime number." : " is not a
prime number."));
}
}
=================================
package com.InterviewPrep;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class RemoveDuplicatesfromListwithoutSetormap {
public static void main(String[] args) {
List<Integer> l = Arrays.asList(1,2,2,2,3,4,5,6,3,4,8,9,12,34,5);
List<Integer> x = l.stream().distinct().collect(Collectors.toList());
System.out.println(x);
}
}
==========================
package com.InterviewPrep;
import java.util.ArrayList;
import java.util.List;
public class RemoveDuplicateWithoutdistinctsetandmap {
public static void main(String[] args) {
List<Integer> l = new ArrayList<>();
l.add(1);
l.add(1);
l.add(2);
l.add(3);
l.add(2);
l.add(4);
l.add(3);
removeduplicates((ArrayList<Integer>) l);
System.out.println("unique elements in list is "+l);
}
public static void removeduplicates(ArrayList<Integer> l){
ArrayList<Integer> al = new ArrayList<>();
for(Integer num :l){
if(!al.contains(num)){
al.add(num);
}
}
l.clear();
l.addAll(al);
}
}
===========================================
package com.InterviewPrep;
public class RemoveOccurancesofChars {
public static void main(String[] args) {
String str = "abadefaghi";
str = str.replace("a","");
System.out.println(str);
}
}
===========================
package com.InterviewPrep;
public class ReverseaNumber {
public static void main(String[] args) {
int n = 123456;
String res = new StringBuilder(String.valueOf(n)).reverse().toString();
System.out.println(res);
// StringBuilder sbl = new StringBuilder();
// sbl.append(n);
// sbl.reverse();
// System.out.println(sbl);
// int n = 987654;
// StringBuffer sb = new StringBuffer(String.valueOf(n));
// System.out.println(sb.reverse());
// int rev =0;
// while (n!=0){
// rev = rev*10+n%10;
// n = n/10;
// System.out.println("Reverse Number is "+rev);
// }
}
}
================================
package com.InterviewPrep;
public class ReverseaString {
public static void main(String[] args) {
String s = "naresh";
// StringBuffer sb = new StringBuffer(s);
// System.out.println(sb.reverse());
// StringBuilder sbl = new StringBuilder(s);
// System.out.println(sbl.reverse());
String rev = "";
int length = s.length();
for(int i = length-1;i>=0;i--){
rev = rev +s.charAt(i);
System.out.println(rev);
}
}
}
=========================
package com.InterviewPrep;
import java.util.LinkedList;
public class ReverseLinkedList {
public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<>();
ll.add(1);
ll.add(2);
ll.add(3);
System.out.println("original order is : "+ll);
LinkedList<Integer> ll1 = new LinkedList<>();
ll.descendingIterator().forEachRemaining(ll1::add);
System.out.println("reverse Order : "+ll1);
}
}
================================
package com.InterviewPrep;
import java.util.*;
public class ReverseLinkedListWithCollection {
public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<>(Arrays.asList(1, 2, 3));
System.out.println("Original order: " + ll);
// Reverse the LinkedList using Collections.reverse
Collections.reverse(ll);
System.out.println("Reversed order: " + ll);
}
}
===================================
package com.InterviewPrep;
import java.util.*;
public class ReverseStringbyGivenInputLength {
public static void main(String[] args) {
String s = "knowledge is power try to improve it";
int strlength = s.length();
Scanner sc = new Scanner(System.in);
// Request user input
System.out.println("Please provide the input number to reverse the String
from:");
int num = sc.nextInt();
// Check if the input number is within valid range
if (num <= strlength && num >= 0) {
// Reverse the substring from index 'num' to the end of the string
StringBuilder sb = new StringBuilder(s.substring(num)).reverse();
// Append the first part of the string unchanged
sb.insert(0, s.substring(0, num));
// Print the result
System.out.println("Modified String: " + sb);
} else {
System.out.println("Entered number input is larger than the string
length or invalid.");
}
// Close the scanner object
sc.close();
}
}
===============================
package com.InterviewPrep;
import java.util.Scanner;
public class ReverseStringByGivenLength {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
System.out.print("Enter number to reverse the string from the given input
length: ");
int len = scanner.nextInt();
if (len <= inputString.length())
// System.out.println("Reversed String: " + new
StringBuilder(inputString.substring(0, len)).reverse() +
inputString.substring(len));
System.out.println("Reversed String: " + inputString.substring(0, len)
+ new StringBuilder(inputString.substring(len)).reverse());
else
System.out.println("Error: Length exceeds string length.");
scanner.close();
}
}
============================
package com.InterviewPrep;
import java.util.Arrays;
public class ReverseStringbyPreservingSpaces {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide an input string.");
return;
}
// Combine all input arguments into a single string
String str = String.join(" ", args);
// Create a character array from the string
char[] result = str.toCharArray();
// Remove spaces and reverse the string
String reversedWithoutSpaces = new StringBuilder(str.replace(" ",
"")).reverse().toString();
int index = 0; // Pointer for characters in the reversed string
for (int i = 0; i < result.length; i++) {
if (result[i] != ' ') { // Replace only non-space characters
result[i] = reversedWithoutSpaces.charAt(index++);
}
}
// Print the final reversed string with spaces preserved
// System.out.println(new String(result));
System.out.println(Arrays.toString(result));
}
}
==================================
package com.InterviewPrep;
import java.util.Scanner;
public class SearchForElement {
public static void main(String[] args) {
int n = 1234567;
System.out.println("input number is : "+n);
System.out.println("Enter number to search in the input vnumber : ");
Scanner sc = new Scanner(System.in);
int searchno = sc.nextInt();
System.out.println((n+"").contains(searchno+ "")?"Search Element found":
"Search Element not found");
}
}
=================================
package com.InterviewPrep;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class SecondLargeNumFromRandomNumbers {
public static void main(String[] args) {
List<Integer> al = Arrays.asList(2,34,45,7,8,12,1,123,7,3,235);
// Collections.sort(al,Collections.reverseOrder());
// System.out.println(al.get(1));
// approach-2
var slarge = al.stream().sorted((a,b)->b-
a).skip(1).findFirst().orElseThrow();
System.out.println(slarge);
}
}
==================================
package com.InterviewPrep;
import java.util.*;
public class SortHashMapByValue {
public static void main(String[] args) {
// Creating a HashMap
HashMap<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Four", 4);
map.put("Three", 3);
map.put("Two", 2);
// Sorting by values
map.entrySet().stream()
.sorted(Map.Entry.comparingByValue()) // Sort by values
.forEach(entry -> System.out.println(entry.getKey() + " = " +
entry.getValue()));
}
}
===================================
package com.InterviewPrep;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class SquareTheNumbers {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5);
// list.stream().map(n->n*n).forEach(System.out::println);
var collect = list.stream().map(n -> n * n).collect(Collectors.toList());
System.out.println(collect);
}
}
======================================
package com.InterviewPrep;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class StreamapiMapExample{
public static void main(String[] args) {
List<Integer> list = Arrays.asList(809,90,112,134,234);
// int max = Collections.max(list);
// System.out.println(max);
int max = list.stream().max(Integer::compareTo).orElseThrow();
System.out.println(max);
// Optional<Integer> maax = list.stream().filter(n->n>100)
// .max(Integer::compareTo);
// maax.ifPresent(System.out::println);
}
}
=================================
package com.InterviewPrep;
public class StringImmutabilityExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = str1; // str2 points to the same object as str1
// Attempt to modify str1
str1 = str1 + " World";
// Print both strings
System.out.println("str1: " + str1); // str1 is modified to "Hello World"
System.out.println("str2: " + str2); // str2 remains "Hello"
}
}
================================
package com.InterviewPrep;
public class StringValuesSameContent {
public static void main(String[] args) {
String emp1 = "Radha";
String emp2 = "Naresh";
String emp3 =emp1;
System.out.println( emp3==emp1);
System.out.println(emp3.equals(emp1));
}
}
==================================
package com.InterviewPrep;
public class SwappingArrayElements {
public static void main(String[] args) {
String [][] x = {{"A","B"},{"C","D"}};
for (int i=x.length-1;i>=0;i--){
for(int j=0;j<x[i].length;j++){
System.out.print(x[i][j]);
}
}
}
}
O/P :: CDAB
=================================
package com.InterviewPrep;
public class SwappingArrayindexvalues {
public static void main(String[] args) {
String [][] s = {{"A","B"},{"C","D"}};
for(int i=0;i<s.length;i++){
for(int j=s[i].length-1;j>=0;j--){
System.out.print(s[i][j]);
}
}
}
O/P :: BADC
======================================
package com.InterviewPrep;
public class SwappingTwoNumbers {
public static void main(String[] args) {
int a = 10;
int b = 20;
// int t =a;
// a=b;
// b=t;
// System.out.print(a+" "+b);
// a= a+b;
// b =a-b;
// a = a-b;
// System.out.print(a+" "+b);
// a= a*b;
// b =a/b;
// a = a/b;
// System.out.print(a+" "+b);
a= a^b;
b= a^b;
a= a^b;
System.out.println(a+ " "+b);
// b =a+b -(a=b);
// System.out.println(a+" "+b);
}
}
=====================
package com.InterviewPrep;
public class SwappingTwoStringsWithOutThirdVariable {
public static void main(String[] args) {
String s1 = "abc";
String s2 = "def";
s1 = s1.concat(s2);
s2 = s1.substring(0,s1.length()-s2.length());
s1 = s1.substring(s2.length());
System.out.println(s1+ ":"+s2);
}
}
================================
package com.InterviewPrep;
import java.util.Arrays;
import java.util.List;
public class TotallingallthevaluesinaList {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(2,4,5,7,88,90);
int sum = list.stream().mapToInt(n->n).sum();
System.out.println(sum);
}
}
===========================
package com.InterviewPrep;
import java.util.Arrays;
import java.util.Collections;
public class TwoMaxElementsFinder {
public static void main(String[] args) {
Integer[] c = {132, 399, 5, 767, 70};
//approach-1
// Arrays.sort(c, Collections.reverseOrder());
// System.out.println(c[0]);
// System.out.println(c[1]);
//approach-2
// Directly sort the array in descending order and take the first two
elements
int[] maxTwo = Arrays.stream(c)
.sorted((a, b) -> b - a) // Sort descending
.mapToInt(Integer::intValue) // Convert back to int
.toArray(); // Collect as an array
// System.out.println("The two largest numbers are: " + maxTwo[0] + " and "
+ maxTwo[1]);
System.out.printf("the two largest numbers are %d & %d%n",
maxTwo[0],maxTwo[1]);
}
}
==============================
package com.InterviewPrep;
public class VowelsPresentChecker {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide an input string.");
return;
}
String s = args[0].toLowerCase();
if (s.matches(".*[aeiou].*")) {
System.out.println("The given input contains vowels.");
} else {
System.out.println("The given input does not contain vowels.");
}
}
}
================================
// Parallelly adding Two lists into new list
package com.InterviewPrep;
import java.util.*;
public class MergeTwoListsAlternatively {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1, 3, 5, 7);
List<Integer> list2 = Arrays.asList(2, 4, 6, 8, 10,12);
// Initialize list3 as a new ArrayList to store the interleaved elements
List<Integer> list3 = new ArrayList<>();
// Get the size of the smaller list to prevent IndexOutOfBoundsException
int size = Math.min(list1.size(), list2.size());
// Interleave elements from both lists
for (int i = 0; i < size; i++) {
list3.add(list1.get(i));
list3.add(list2.get(i));
}
// If list1 is longer, add the remaining elements
if (list1.size() > size) {
list3.addAll(list1.subList(size, list1.size()));
}
// If list2 is longer, add the remaining elements
if (list2.size() > size) {
list3.addAll(list2.subList(size, list2.size()));
}
// Print the interleaved list
System.out.println(list3);
}
}
=================================
// Remove Duplicates from String
import java.util.*;
public class FrequencyLettersRemove{
public static void main(String [] args){
String str = "abcabcdefghi";
Set<Character> hs = new HashSet<>();
for(char ch : str.toCharArray()){
hs.add(ch);
}
StringBuilder sb = new StringBuilder();
for(Character st : hs){
sb.append(st);
}
System.out.println(sb.toString());
}
===================================================
// Compare Two Strings WithOut Comparable and Comparator
package com.InterviewPrep;
import java.util.Objects;
public class CompareStringsWithOutComparableandComparator {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "hello";
if (Objects.equals(str1, str2)) {
System.out.println("Strings are equal.");
} else {
System.out.println("Strings are not equal.");
}
}
}
==================================
// Write Odd and Even Numbers Using Two Threads
package com.InterviewPrep;
public class OddEven {
private static final Object lock = new Object();
public static void main(String[] args) {
Thread oddThread = new Thread(() -> {
for (int i = 1; i <= 9; i += 2) {
synchronized (lock) {
System.out.println(i);
lock.notify();
try { lock.wait(); } catch (InterruptedException e) {}
}
}
});
Thread evenThread = new Thread(() -> {
for (int i = 2; i <= 10; i += 2) {
synchronized (lock) {
System.out.println(i);
lock.notify();
try { lock.wait(); } catch (InterruptedException e) {}
}
}
});
oddThread.start();
evenThread.start();
}
}
===============================
// Print Names and count Using java 8
import java.util.*;
import java.util.stream.*;
public class CountWords{
public static void main(String [] args){
String [] s =
{"Anjaneya","RamaChandra","Krishna","Gopala","Mukunda","Krishna"};
Map<String,Long> res = Arrays.stream(s).collect(Collectors.groupingBy(w-
>w,Collectors.counting()));
res.forEach((w,c)->System.out.println(w+"="+c));
}
}
=============================================
// Remove duplicate from a list of employee object based on empID using streams
import java.util.*;
import java.util.stream.Collectors;
class Employee {
private int empID;
private String name;
public Employee(int empID, String name) {
this.empID = empID;
this.name = name;
}
public int getEmpID() {
return empID;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Employee{" + "empID=" + empID + ", name='" + name + '\'' + '}';
}
}
public class Main {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee(101, "John"),
new Employee(102, "Alice"),
new Employee(101, "John"),
new Employee(103, "Bob"),
new Employee(102, "Alice")
);
List<Employee> uniqueEmployees = employees.stream()
.collect(Collectors.toMap(Employee::getEmpID, e -> e, (e1, e2) ->
e1))
.values()
.stream()
.collect(Collectors.toList());
uniqueEmployees.forEach(System.out::println);
}
}
============================================