Table of Contents
ToggleWrite a method that will take one string as an argument and will return the reverse version of this string.
- We create a
StringBuilder
object to build the reversed string. - We iterate through the characters of the input string from the end to the beginning using a
for
loop. - Inside the loop, we append each character to the
StringBuilder
. - Finally, we return the reversed string by converting the
StringBuilder
to a string usingtoString()
method.
public class StringReverser {
public static String reverseString(String input) {
StringBuilder reversed = new StringBuilder();
for (int i = input.length() - 1; i >= 0; i--) {
reversed.append(input.charAt(i));
}
return reversed.toString();
}
public static void main(String[] args) {
String originalString = "Hello, world!";
String reversedString = reverseString(originalString);
System.out.println(reversedString); // Output: "!dlrow ,olleH"
}
}
2. Write a method that will take an array as an argument and reverse it.
- We use two pointers,
start
andend
, initialized to the first and last indices of the array respectively. - We iterate through the array while
start
is less thanend
. - In each iteration, we swap the elements at indices
start
andend
, effectively reversing the array. - We increment
start
and decrementend
to move towards the center of the array. - Finally, we print the reversed array.
public class ArrayReverser {
public static void reverseArray(int[] arr) {
int start = 0;
int end = arr.length - 1;
while (start < end) {
// Swap elements at start and end indices
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// Move towards the center of the array
start++;
end--;
}
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
reverseArray(array);
System.out.println("Reversed array:");
for (int num : array) {
System.out.print(num + " ");
}
// Output: 5 4 3 2 1
}
}
3. Write a method that will take a string as an argument. The method will reverse the position of words and return it.
- We split the input string into an array of words using the
split()
method, with the regular expression\\s+
to split on whitespace. - We create a
StringBuilder
to store the reversed string. - We iterate through the words array in reverse order, appending each word to the
StringBuilder
. - We append a space after each word except for the last one.
- Finally, we convert the
StringBuilder
to a string and return it.
public class WordReverser {
public static String reverseWords(String input) {
// Split the input string into words
String[] words = input.split("\\s+");
// Create a StringBuilder to store the reversed string
StringBuilder reversed = new StringBuilder();
// Iterate through the words array in reverse order
for (int i = words.length - 1; i >= 0; i--) {
// Append each word to the StringBuilder with a space
reversed.append(words[i]);
// If it's not the first word, append a space
if (i != 0) {
reversed.append(" ");
}
}
// Convert StringBuilder to String and return
return reversed.toString();
}
public static void main(String[] args) {
String inputString = "Hello world! How are you?";
String reversedString = reverseWords(inputString);
System.out.println(reversedString); // Output: "you? are How world! Hello"
}
}
4. Write a code for string palindrome (A palindrome is a word, phrase, number, or sequence of words that reads the same backward as forward.)
- We convert the input string to lowercase to ignore case sensitivity.
- We initialize two pointers,
start
andend
, pointing to the beginning and end of the string respectively. - We loop until
start
is less thanend
. - In each iteration, we compare characters at
start
andend
indices. If they’re not equal, we returnfalse
, indicating that the string is not a palindrome. - If the loop completes without returning
false
, it means the string is a palindrome, so we returntrue
.
public class PalindromeChecker {
public static boolean isPalindrome(String str) {
// Convert the string to lowercase to ignore case sensitivity
str = str.toLowerCase();
// Initialize pointers for the start and end of the string
int start = 0;
int end = str.length() - 1;
// Loop until the pointers meet
while (start < end) {
// If characters at start and end indices are not equal, it's not a palindrome
if (str.charAt(start) != str.charAt(end)) {
return false;
}
// Move the pointers towards the center of the string
start++;
end--;
}
// If the loop completes without returning false, the string is a palindrome
return true;
}
public static void main(String[] args) {
String str = "radar";
if (isPalindrome(str)) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + " is not a palindrome.");
}
// Output: radar is a palindrome.
}
}
5. Write a code for number palindrome (A palindrome is a word, phrase, number, or sequence of words that reads the same backward as forward.)
- We store the original number in a variable (
originalNumber
) to compare later. - We initialize another variable
reversedNumber
to store the reversed version of the number. - We loop through each digit of the number by continuously dividing the number by 10 and extracting the last digit.
- Inside the loop, we build the reversed number by multiplying the existing reversed number by 10 and adding the current digit.
- After the loop, we compare the original number with the reversed number. If they are equal, the number is a palindrome.
public class PalindromeChecker {
public static boolean isPalindrome(int number) {
int originalNumber = number;
int reversedNumber = 0;
while (number > 0) {
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number /= 10;
}
return originalNumber == reversedNumber;
}
public static void main(String[] args) {
int num = 12321;
if (isPalindrome(num)) {
System.out.println(num + " is a palindrome.");
} else {
System.out.println(num + " is not a palindrome.");
}
// Output: 12321 is a palindrome.
}
}
6. Write a method that will accept an array of int as an argument and it returns the max and min number from a given array.
- We initialize
min
andmax
variables with the first element of the array. - We iterate through the array starting from the second element.
- During each iteration, we update the
min
andmax
values if we find a smaller or larger number, respectively. - Finally, we return an array containing the maximum and minimum numbers.
public class MaxMinFinder {
public static int[] findMaxMin(int[] array) {
if (array == null || array.length == 0) {
return new int[]{};
}
int min = array[0];
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
if (array[i] > max) {
max = array[i];
}
}
return new int[]{max, min};
}
public static void main(String[] args) {
int[] numbers = {5, 3, 9, 2, 7, 1};
int[] maxMin = findMaxMin(numbers);
System.out.println("Maximum number: " + maxMin[0]);
System.out.println("Minimum number: " + maxMin[1]);
// Output:
// Maximum number: 9
// Minimum number: 1
}
}
7. Write a method that accepts int array as an argument and returns second or nth min and max number from the given array.
- We first check if the array is null or if the value of n is invalid (less than 1 or greater than the length of the array). If so, we return an empty array.
- We sort the array in ascending order using
Arrays.sort()
. - We return an array containing the nth smallest and nth largest numbers, accessed by indexing
array[n - 1]
andarray[array.length - n]
, respectively.
import java.util.Arrays;
public class NthMinMaxFinder {
public static int[] findNthMinMax(int[] array, int n) {
if (array == null || array.length < n || n < 1) {
return new int[]{};
}
// Sort the array in ascending order
Arrays.sort(array);
// Return the nth smallest and nth largest numbers
return new int[]{array[n - 1], array[array.length - n]};
}
public static void main(String[] args) {
int[] numbers = {5, 3, 9, 2, 7, 1};
int n = 2;
int[] nthMinMax = findNthMinMax(numbers, n);
System.out.println("Second smallest number: " + nthMinMax[0]);
System.out.println("Second largest number: " + nthMinMax[1]);
// Output:
// Second smallest number: 2
// Second largest number: 7
}
}
8. Swap values of two variables without direct reassignment and without creating any extra variables.
You can swap the values of two variables without directly reassigning them or creating extra variables by using arithmetic operations.
- Add the values of both variables and store the result in one of the variables (
a = a + b
). - Subtract the value of the second variable (the original value of
b
) from the result, and assign this value to the second variable (b = a - b
). Now,b
holds the original value ofa
. - Finally, subtract the new value of
b
(which is the original value ofa
) from the new value ofa
(which is the sum of the original values ofa
andb
). This result is the original value ofb
, and assign it toa
(a = a - b
).
public class VariableSwapper {
public static void main(String[] args) {
int a = 5;
int b = 10;
System.out.println("Before swapping: a = " + a + ", b = " + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping: a = " + a + ", b = " + b);
}
}
9. Write a method that accepts one string argument and returns it without duplicates.
- We use a
LinkedHashSet
to store unique characters while preserving the order of insertion. - We iterate through each character of the input string and add it to the set.
- After adding all characters to the set, we construct the resulting string by iterating through the set and appending each character to a
StringBuilder
. - Finally, we return the resulting string without duplicates.
import java.util.LinkedHashSet;
public class StringDuplicateRemover {
public static String removeDuplicates(String input) {
// Use LinkedHashSet to preserve the order of characters
LinkedHashSet<Character> set = new LinkedHashSet<>();
// Iterate through each character of the input string
for (char ch : input.toCharArray()) {
// Add the character to the set (which automatically eliminates duplicates)
set.add(ch);
}
// Convert the set to a string
StringBuilder result = new StringBuilder();
for (char ch : set) {
result.append(ch);
}
return result.toString();
}
public static void main(String[] args) {
String inputString = "hello world";
String resultString = removeDuplicates(inputString);
System.out.println("String without duplicates: " + resultString);
// Output: String without duplicates: helo wrd
}
}
10. Write a method that accepts two string arguments and returns true if they are anagram and false if they are not.
Two string anagram. An anagram is when all the letters in one string exist in another but the order of letters does not matter.
- We first remove any spaces and convert both strings to lowercase to make the comparison case-insensitive and space-insensitive.
- Then, we compare the lengths of the two strings. If they are different, they cannot be anagrams, so we return false.
- Next, we convert both strings to character arrays and sort them.
- Finally, we compare the sorted arrays using
Arrays.equals()
method. If they are equal, the strings are anagrams, so we return true; otherwise, we return false.
import java.util.Arrays;
public class AnagramChecker {
public static boolean areAnagrams(String str1, String str2) {
// Remove spaces and convert to lowercase
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
// If lengths are different, they cannot be anagrams
if (str1.length() != str2.length()) {
return false;
}
// Convert strings to character arrays and sort them
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
// Compare sorted arrays
return Arrays.equals(charArray1, charArray2);
}
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.");
}
// Output: listen and silent are anagrams.
}
}