============================================ Reverse the String [anil --> lina]
public class Main
{
public static void main(String[] args) {
String str = "geeksforgeeks";
String revStr="";
for(char c:str.toCharArray())
{
revStr=c+revStr;
}
System.out.println(revStr);
}
============================================ Reverse the String [how to do in java
--> woh ot od ni avaj ]
Original string : how to do in java
Reversed string : woh ot od ni avaj
public class Main
{
public static void main(String[] args) {
String originalStr = "how to do in java";
String words[] = originalStr.split(" ");
for (int i = 0; i < words.length; i++)
{
String revStr="";
for(char c:words[i].toCharArray())
{
revStr=c+revStr;
}
System.out.print(revStr+" ");
}
}
}
============================================ Reverse the String [how to do in java
--> java in do to how]
public static void main(String[] args) {
String originalStr = "how to do in java";
String words[] = originalStr.split(" ");
String reversedString = "";
for (int i = words.length-1; i >= 0; i--) {
reversedString = reversedString+words[i]+ " ";
}
System.out.print(reversedString);
}
============================================ Reverse the String With Capitalization
Input: how to do in java
Output: Java In Do To How
public static void main(String[] args) {
String originalStr = "how to do in java anil";
String words[] = originalStr.split(" ");
String reversedString = "";
for (int i = words.length - 1; i >= 0; i--) {
char firstLetter = Character.toUpperCase(words[i].charAt(0));
reversedString += firstLetter + words[i].substring(1) + " ";
}
System.out.print(reversedString.trim());
}
============================================ Fibonacci Series [0 1 1 2 3 5 8 13 21
34]
public class LetsSolveIt {
public static void main(String[] args) {
int n = 10;
printFibonacciSeries(n);
}
public static void printFibonacciSeries(int n) {
int prev = 0;
int curr = 1;
System.out.println("Fibonacci Series up to " + n + ":");
System.out.print(prev + " " + curr + " ");
for (int i = 2; i < n; i++) {
int next = prev + curr;
System.out.print(next + " ");
prev = curr;
curr = next;
}
}
}
============================================ Fibonacci Series Using recursion
public class LetsSolveIt {
public static void main(String[] args) {
int n = 10;
System.out.println("Fibonacci Series up to " + n + ":");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
============================================ Find Prime Number
public class LetsSolveIt {
public static void main(String[] args) {
int number = 17;
if (isPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
public static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
============================================ Print Prime No
public class LetsSolveIt {
public static void main(String[] args) {
int num = 30;
int count;
for (int i = 2; i <= num; i++) {
count = 0;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
count++;
break;
}
}
if (count == 0) {
System.out.println(i);
}
}
}
}
============================================ Palindrome Number : 121
public class Main {
public static void main(String[] args) {
int number = 111;
int temp=number;
int sum=isPalindrome(number);
if(temp==sum)
{
System.out.println(number + " is a Palindrome.");
}
else
{
System.out.println(number + " is a Not Palindrome.");
}
}
public static int isPalindrome(int number)
{
int rev=0;
int sum=0;
while(number>0)
{
rev=number%10;
sum=(sum*10)+rev;
number=number/10;
}
return sum;
}
}
============================================ Palindrome String: abba
public class Main {
public static void main(String[] args) {
String str = "abba";
String tempStr=isPalindrome(str);
if(tempStr.equals(str))
{
System.out.println(str + " is a Palindrome.");
}
else
{
System.out.println(str + " is a Not Palindrome.");
}
}
public static String isPalindrome(String str)
{
String revStr="";
for(char c:str.toCharArray())
{
revStr=c+revStr;
}
return revStr;
}
}
============================================ To check Armstrong
125: 1^3 + 2^3 + 5^3 = 1 + 8 + 125 = 134 (Not an Armstrong Number)
1634: 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634 (Armstrong Number)
public class Main
{
public static void main(String[] args) {
int number = 1634;
if (isArmstrongNumber(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}
static boolean isArmstrongNumber(int number) {
int originalNumber = number;
int numOfDigits = String.valueOf(number).length();
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += Math.pow(digit, numOfDigits);
number = number/10;
}
return sum == originalNumber;
}
}
============================================ Anagram Using In-Built Methods
Two strings are said to be anagram if we can form one string by arranging the
characters of another string.
For example, Race and Care.
public class AnagramCheck {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
if (areAnagrams(str1, str2)) {
System.out.println(str1 + " and " + str2 + " are anagrams.");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams.");
}
}
public static boolean areAnagrams(String str1, String str2) {
// Remove whitespace and convert strings to lowercase
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
// If lengths are not equal, they cannot be anagrams
if (str1.length() != str2.length()) {
return false;
}
// Convert strings to char arrays and sort them
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
// Compare sorted char arrays
return Arrays.equals(charArray1, charArray2);
}
}
============================================ Anagram Without Without In Built
Methods
import java.util.HashMap;
public class AnagramCheck {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
if (areAnagrams(str1, str2)) {
System.out.println(str1 + " and " + str2 + " are anagrams.");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams.");
}
}
public static boolean areAnagrams(String str1, String str2) {
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
if (str1.length() != str2.length()) {
return false;
}
HashMap<Character, Integer> charCount = new HashMap<>();
for (char c : str1.toCharArray()) {
if (charCount.containsKey(c)) {
charCount.put(c, charCount.get(c) + 1);
} else {
charCount.put(c, 1);
}
}
for (char c : str2.toCharArray()) {
if (!charCount.containsKey(c)) {
return false;
}
charCount.put(c, charCount.get(c) - 1);
if (charCount.get(c) == 0) {
charCount.remove(c);
}
}
return charCount.isEmpty();
}
}
============================================ Count the occurrence of each character
in a string.
import java.io.*;
import java.util.*;
class OccurrenceOfCharInString {
static void characterCount(String inputString)
{
HashMap<Character, Integer> charCountMap = new HashMap<Character,
Integer>();
char[] strArray = inputString.toCharArray();
for (char c : strArray) {
if (charCountMap.containsKey(c)) {
charCountMap.put(c, charCountMap.get(c) + 1);
}
else {
charCountMap.put(c, 1);
}
}
for (Map.Entry entry : charCountMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
public static void main(String[] args)
{
String str = "Ajit";
characterCount(str);
}
}
============================================ Remove Duplicates from Sorted
Array/Return no of unique elements in an array.
Input: nums = [1,1,2] & Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums
being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are
underscores).
class Solution {
public int removeDuplicates(int[] nums) {
int count = 1;
for(int i=1;i<nums.length;i++){
if(nums[i] != nums[i-1]){
nums[count] = nums[i];
count++;
}
}
return count;
}
}
=========================================== Remove Duplicates from UnSorted
public class LetsSolveIt {
public static void removeDuplicates(int[] a) {
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
// adding elements to LinkedHashSet
for (int i = 0; i < a.length; i++)
set.add(a[i]);
// Print the elements of LinkedHashSet
System.out.print(set);
}
public static void main(String[] args) {
int a[] = { 5, 2, 6, 8, 6, 7, 5, 2, 8 };
// Function call
removeDuplicates(a);
}
}
============================================ Print the array without duplicate
public class RemoveDuplicatesFromArrayWithCount {
public static void main(String[] args) {
int[] sortedArray = {1, 1, 2, 2, 3, 4, 4, 5, 6, 6};
int n = sortedArray.length;
int j = 0;
int duplicateCount = 0;
for (int i = 0; i < n - 1; i++) {
if (sortedArray[i] != sortedArray[i + 1]) {
sortedArray[j] = sortedArray[i];
j++;
} else {
duplicateCount++;
}
}
sortedArray[j] = sortedArray[n - 1]; // Copy the last element to the end of
the modified array
int lengthWithoutDuplicates = j + 1; // Updated length of array without
duplicates
// Print the array without duplicates
System.out.println("Array without duplicates:");
for (int k = 0; k < lengthWithoutDuplicates; k++) {
System.out.print(sortedArray[k] + " ");
}
// Print the count of duplicate elements
System.out.println("\nCount of duplicate elements: " + duplicateCount);
}
}
============================================ Two Sum [return array of indices]
Input: nums = [2,7,11,15], target = 9 & Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
import java.util.*;
class Solution
{
public int[] twoSum(int[] nums, int target)
{
Map<Integer, Integer> maps = new HashMap();
for(int i=0;i<nums.length;i++)
{
int requiredSum=target-nums[i];
if(maps.containsKey(requiredSum))
{
return new int[] {maps.get(requiredSum),i};
}
maps.put(nums[i],i);
}
return new int[] {};
}
}
============================================ Two Sum [return array of values]
import java.util.*;
class Solution
{
public int[] twoSum(int[] nums, int target)
{
Map<Integer, Integer> maps = new HashMap();
for(int i=0;i<nums.length;i++)
{
int requiredSum=target-nums[i];
if(maps.containsKey(requiredSum))
{
return new int[] {nums[maps.get(requiredsum)],nums[i]};
}
maps.put(nums[i],i);
}
return new int[] {};
}
}
============================================ Remove Element [Return no of unique
elements]
Input: nums = [3,2,2,3], val = 3 & Output: 2, nums = [2,2,_,_]
class Solution {
public int removeElement(int[] nums, int val) {
int count = 0;
for(int i=0;i<nums.length;i++){
if(nums[i] != val){
nums[count] = nums[i];
count++;
}
}
return count;
}
}
============================================ Merge Sorted Array
You are given two integer arrays nums1 and nums2, sorted in increasing order, and
two integers m and n, representing the number of elements in nums1 and nums2
respectively.
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
public class MergeSortedArray {
public static void main(String[] args) {
int[] nums1 = {1, 2, 3, 0, 0, 0};
int m = 3;
int[] nums2 = {2, 5, 6};
int n = 3;
merge(nums1, m, nums2, n);
System.out.print("Merged Array: ");
for (int num : nums1) {
System.out.print(num + " ");
}
}
public static void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1;
int j = n - 1;
int k = m + n - 1;
while (j >= 0) {
if (i >= 0 && nums1[i] > nums2[j]) {
nums1[k] = nums1[i];
i--;
} else {
nums1[k] = nums2[j];
j--;
}
k--;
}
}
}
============================================ Valid Paranthesis
class Solution {
public boolean isValid(String s) {
// Create an empty stack to keep track of opening brackets
Stack<Character> stack = new Stack<Character>();
// Loop through every character in the string
for (char c : s.toCharArray()) {
// If the character is an opening bracket, push it onto the stack
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else { // If current character is not opening bracket, then it must
be closing. So stack cannot be empty at this point.
if (stack.isEmpty()) {
return false;
}
// Otherwise, get the top of the stack and check if it's the
matching opening bracket
char top = stack.peek();
if ((c == ')' && top == '(') || (c == ']' && top == '[') || (c ==
'}' && top == '{')) {
// If it is, pop the opening bracket from the stack
stack.pop();
} else { // Otherwise, the brackets don't match, so return false
return false;
}
}
}
// If the stack is empty, all opening brackets have been closed, so return
true
// Otherwise, there are unmatched opening brackets, so return false
return stack.isEmpty();
}
}
============================================ Print all subsequences/substrings of a
string
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter String: ");
String str = sc.nextLine();
System.out.println("All substrings are:" );
for(int i=0;i<str.length();i++){
for(int j=i+1;j<=str.length();j++){
StringBuilder strBuilder = new StringBuilder();
for(int k=i;k<j;k++){
strBuilder.append(str.charAt(k));
}
System.out.println(strBuilder.toString());
}
}
}
}
============================================ Find the Index of the First Occurrence
Of 2nd String in 1st String
class Solution {
public int strStr(String haystack, String needle) {
int hl=haystack.length();
int nl=needle.length();
if(hl<nl)
return -1;
for(int i=0;i<=hl-nl;i++){
int j=0;
while(j<nl && haystack.charAt(i+j)==needle.charAt(j)){
j++;
}
if(j==needle.length()){
return i;
}
}
return -1;
}
}
============================================ Rotates an array to the right by k
steps
Input: {1, 2, 3, 4, 5, 6, 7} and k = 3
Output: [5, 6, 7, 1, 2, 3, 4]
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums1 = {1, 2, 3, 4, 5, 6, 7};
int k1 = 3;
rotate(nums1, k1);
System.out.println("Rotated array: " + Arrays.toString(nums1));
}
public static void rotate(int[] nums, int k) {
int n = nums.length;
k %= n; // Calculate the effective number of rotations
// Reverse the entire array
reverse(nums, 0, n - 1);
// Reverse the first k elements
reverse(nums, 0, k - 1);
// Reverse the remaining elements after the first k elements
reverse(nums, k, n - 1);
}
// Helper function to reverse an array or a portion of an array
private static void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
============================================ Rotates an array to the left by k
steps
public class LeftRotation {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6, 7};
int k = 3;
rotateLeft(nums, k);
System.out.print("Left rotated array: ");
// To Print
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void rotateLeft(int[] nums, int k) {
int n = nums.length;
k %= n; // Calculate the effective number of rotations
// Reverse the first n - k elements
reverse(nums, 0, n - k - 1);
// Reverse the last k elements
reverse(nums, n - k, n - 1);
// Reverse the entire array
reverse(nums, 0, n - 1);
}
// Helper function to reverse an array or a portion of an array
private static void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}
============================================ Max Min
public class LetsSolveIt {
public static int[] findMaxMin(int[] myList) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int[] newArr = new int[2];
for (int i = 0; i < myList.length; i++) {
if (myList[i] > max) {
max = myList[i];
}
if (myList[i] < min) {
min = myList[i];
}
newArr[0] = max;
newArr[1] = min;
}
return newArr;
public static void main(String[] args) {
int[] myList1 = { 5, 3, 8, 1, 6, 9 };
int[] result1 = findMaxMin(myList1);
System.out.println("Test case 1: MaxMin: " + Arrays.toString(result1)); //
prints "[9, 1]"
}
=========================================== Max Profit
public class LetsSolveIt {
public static int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1) {
return 0;
}
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minPrice)
minPrice = prices[i];
else if (prices[i] - minPrice > maxProfit)
maxProfit = prices[i] - minPrice;
}
return maxProfit;
}
public static void main(String[] args) {
int[] prices = { 7, 1, 5, 3, 6, 4 };
int profit = maxProfit(prices);
System.out.println("Test case 1: Maximum profit: " + profit); // prints
"Maximum profit: 5"
}
}
============================================ Longest String
public class LetsSolveIt {
public static String findLongestString(String[] array) {
String longest = "";
for (String str : array) {
if (str.length() > longest.length()) {
longest = str;
}
}
return longest;
}
public static void main(String[] args) {
String[] stringList1 = { "apple", "banana", "kiwi", "pear" };
String longest1 = findLongestString(stringList1);
System.out.println("Test case 1: Longest string: " + longest1);
}
}
============================================ Longest Happy String
public class LongestHappyString {
public static void main(String[] args) {
int a = 1, b = 1, c = 7;
System.out.println(longestHappyString(a, b, c));
}
public static String longestHappyString(int a, int b, int c) {
StringBuilder result = new StringBuilder();
int totalLength = a + b + c;
char prevChar = '-';
while (totalLength > 0) {
char nextChar = findNextChar(a, b, c, prevChar);
if (nextChar == '-') break; // No valid character found
result.append(nextChar);
totalLength--;
// Update counts
if (nextChar == 'a') a--;
else if (nextChar == 'b') b--;
else if (nextChar == 'c') c--;
prevChar = nextChar;
}
return result.toString();
}
private static char findNextChar(int a, int b, int c, char prevChar) {
if (prevChar == 'a') {
if (b >= c && b > 0) return 'b';
else if (c > 0) return 'c';
else if (b > 0) return 'b';
} else if (prevChar == 'b') {
if (a >= c && a > 0) return 'a';
else if (c > 0) return 'c';
else if (a > 0) return 'a';
} else if (prevChar == 'c') {
if (a >= b && a > 0) return 'a';
else if (b > 0) return 'b';
else if (a > 0) return 'a';
} else {
if (a >= b && a >= c && a > 0) return 'a';
else if (b >= c && b > 0) return 'b';
else if (c > 0) return 'c';
else if (b > 0) return 'b';
else if (a > 0) return 'a';
}
return '-'; // No valid character found
}
}
============================================ Longest Palindromic String
public class LongestPalindromicSubstring {
public static void main(String[] args) {
String str = "babad";
System.out.println(longestPalindrome(str)); // Output: "bab" or "aba"
}
public static String longestPalindrome(String s) {
if (s == null || s.length() < 1) return "";
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i); // For odd length palindromes
int len2 = expandAroundCenter(s, i, i + 1); // For even length
palindromes
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
private static int expandAroundCenter(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) ==
s.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}
}
============================================ Max Sub Array
import java.util.Arrays;
public class Main {
public static int maxSubarray(int[] nums) {
if (nums == null || nums.length == 0) {
return 0; // Return 0 for empty array
}
int maxSum = nums[0]; // Initialize maxSum with the first element
int currentSum = nums[0]; // Initialize currentSum with the first element
// Iterate through the array starting from the second element
for (int i = 1; i < nums.length; i++) {
// Update currentSum to include the current element if it improves the
sum
currentSum = Math.max(nums[i], currentSum + nums[i]);
// Update maxSum if the currentSum is greater
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
public static void main(String[] args) {
// Example 1: Simple case with positive and negative numbers
int[] inputCase1 = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int result1 = maxSubarray(inputCase1);
System.out.println("Example 1: Input: " + Arrays.toString(inputCase1) + "\
nResult: " + result1);
}