Prep - Coding
Prep - Coding
Algorithm:
Algorithm:
1. Initialize variables max and min with the first element of the array.
Algorithm:
3. If the current element is equal to the target element, set contains to true and break out of
the loop.
4. Print whether the array contains the target element based on the value of contains.
4. Reverse an Array:
Algorithm:
1. Initialize variables start to 0 and end to the last index of the array.
2. Use a while loop with the condition start < end to swap elements at positions start and end.
Algorithm:
3. If the current element is equal to the target, return the current index.
Algorithm:
3. If any element is greater than the next one, the array is not sorted.
4. If the loop completes without finding such elements, the array is sorted.
Algorithm:
3. If the element is not in the set, add it to the set and print it.
import java.util.HashSet;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] numbers = {3, 7, 2, 8, 7, 3, 1, 2};
removeDuplicates(numbers);
}
private static void removeDuplicates(int[] arr) {
HashSet<Integer> uniqueSet = new HashSet<>();
for (int num : arr) {
if (uniqueSet.add(num)) {
System.out.print(num + " ");
}
}
}
}
Algorithm:
import java.util.HashMap;
public class CountOccurrences {
public static void main(String[] args) {
int[] numbers = {3, 7, 2, 8, 7, 3, 1, 2};
countOccurrences(numbers);
}
private static void countOccurrences(int[] arr) {
HashMap<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : arr) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
for (int num : frequencyMap.keySet()) {
System.out.println("Element: " + num + ", Frequency: " + frequencyMap.get(num));
}
}
}
Algorithm:
1. Calculate the effective rotation by taking the remainder when dividing k by the array length
(k % arr.length).
Algorithm:
3. For each element, if it’s greater than max, update max and print the element.
public class LeadersInArray {
public static void main(String[] args) {
int[] numbers = {16, 17, 4, 3, 5, 2};
findLeaders(numbers);
}
private static void findLeaders(int[] arr) {
int max = arr[arr.length - 1];
System.out.println("Leader: " + max);
for (int i = arr.length - 2; i >= 0; i--) {
if (arr[i] > max) {
max = arr[i];
System.out.println("Leader: " + max);
}
}
}
}
Given an array containing n distinct numbers taken from the range 0 to n, find the one missing from
the array.
Algorithm:
1. Calculate the expected sum of the first n natural numbers using the formula n * (n + 1) / 2
2. Calculate the actual sum of the elements in the array using a ‘for’ loop.