Java Programs
Java Programs
1. Reverse a String
To reverse a string, we can iterate from the end of the string to the beginning and construct a new
string.
Two strings are anagrams if they contain the same characters in the same frequency.
We can use a sliding window technique to find the longest substring without repeating
characters.
To compress a string, we count the consecutive characters and form a new string.
To check if one string is a rotation of another, we can concatenate the first string with itself and
see if the second string is a substring of this concatenated string.
To count vowels and consonants in a string, we can iterate through the string and check each
character.
A pangram is a string that contains every letter of the alphabet at least once.
Arrays
To find pairs of integers that sum up to a target, we can use a nested loop.
To rotate an array to the right by a given number of steps, we can use a reverse approach.
return result;
}
To find the missing number in an array, we can use the sum formula for the first N natural
numbers.
To find the contiguous subarray with the largest sum, we can use Kadane's algorithm.
return maxSoFar;
}
To calculate the product of the array except self, we can use two passes.
public class ProductExceptSelf {
public static int[] productExceptSelf(int[] arr) {
int n = arr.length;
int[] leftProducts = new int[n];
int[] rightProducts = new int[n];
int[] result = new int[n];
leftProducts[0] = 1;
for (int i = 1; i < n; i++) {
leftProducts[i] = leftProducts[i - 1] * arr[i - 1];
}
rightProducts[n - 1] = 1;
for (int i = n - 2; i >= 0; i--) {
rightProducts[i] = rightProducts[i + 1] * arr[i + 1];
}
return result;
}
To move zeroes to the end of an array, we can use the two-pointer technique.