1. HOW MANY TIMES NUMBEROCCUR
import java.util.*;
public class Main {
public static void main(String[]
args) {
int[] arr = {2, 3, 2, 4, 5, 3, 4, 4};
Map<Integer, Integer> map =
new HashMap<>();
for (int num : arr) map.put(num,
map.getOrDefault(num, 0) + 1);
map.forEach((k, v) ->
System.out.println(k + " occurs " + v
+ " times."));
}
}
2. HOW MANY TIMES DIGIT OCCUR
import java.util.*;
public class Main {
public static void main(String[]
args) {
String s = "Hello
World".toLowerCase().replaceAll("[
^a-z]", "");
Map<Character, Integer> m =
new HashMap<>();
for (char c : s.toCharArray())
m.put(c, m.getOrDefault(c, 0) + 1);
m.forEach((k, v) ->
System.out.println(k + " = " + v));
} }
3. import java.util.*; //zero to last
public class Main {
public static void main(String[]
args) {
int[] arr = {0, 1, 0, 3, 12};
int index = 0;
for (int num : arr) if (num != 0)
arr[index++] = num;
while (index < arr.length)
arr[index++] = 0;
System.out.println(Arrays.toString(
arr)); }}
4. ascending order and descding order
import java.util.*;
public class Main {
public static void main(String[] args) {
Integer[] a = {5, 2, 9, 1, 7};
Arrays.sort(a); // Ascending
System.out.println("Asc: " +
Arrays.toString(a));
Arrays.sort(a, Collections.reverseOrder())
// Descending
System.out.println("Desc: " +
Arrays.toString(a));
}
}
5. LINEAR SEARCH
public class LinearSearchShort {
public static void main(String[] args) {
int[] arr = {5, 8, 2, 9, 4};
int target = 9;
boolean found = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
System.out.println("Found at index " + i);
found = true;
break;
}
}
if (!found)
System.out.println("Not found"); } }
6. BINARY SEARCH
public class BinarySearchSimple {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9}; // already sorted
int target = 5;
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) {
System.out.println("Found at index " + mid);
return;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
} System.out.println("Not found"); }}