90 coding interview questions with their answers using Java 8 or above.
Basic Syntax and Data Structures
1. Reverse a String
java
Copy code
public class ReverseString {
public static void main(String[] args) {
String str = "hello";
String reversed = new
StringBuilder(str).reverse().toString();
System.out.println(reversed); // Output: "olleh"
}
}
2. Find the Factorial of a Number
java
Copy code
public class Factorial {
public static void main(String[] args) {
int number = 5;
int factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println(factorial); // Output: 120
}
}
3. Check if a Number is Prime
java
Copy code
public class PrimeNumber {
public static void main(String[] args) {
int number = 29;
boolean isPrime = true;
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
System.out.println(isPrime); // Output: true
}
}
4. Find the Fibonacci Series up to N Terms
java
Copy code
public class Fibonacci {
public static void main(String[] args) {
int n = 10;
int a = 0, b = 1;
System.out.print(a + " " + b);
for (int i = 2; i < n; i++) {
int next = a + b;
System.out.print(" " + next);
a = b;
b = next;
}
}
}
5. Find the Largest Element in an Array
java
Copy code
public class LargestElement {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9};
int max = arr[0];
for (int i : arr) {
if (i > max) {
max = i;
}
}
System.out.println(max); // Output: 9
}
}
Java 8 Features
6. Use a Lambda Expression to Sort a List
java
Copy code
import java.util.*;
public class LambdaSort {
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Jane", "Alex",
"Chris");
Collections.sort(names, (a, b) -> a.compareTo(b));
System.out.println(names); // Output: [Alex, Chris, Jane,
John]
}
}
7. Filter a List using Streams
java
Copy code
import java.util.*;
import java.util.stream.*;
public class FilterList {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8,
9, 10);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers); // Output: [2, 4, 6, 8, 10]
}
}
8. Compute Sum of a List of Integers Using Streams
java
Copy code
import java.util.*;
import java.util.stream.*;
public class SumList {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println(sum); // Output: 15
}
}
9. Find the Maximum Value in a List Using Streams
java
Copy code
import java.util.*;
import java.util.stream.*;
public class MaxValue {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int max = numbers.stream().max(Integer::compare).get();
System.out.println(max); // Output: 5
}
}
10. Create and Use Optional in Java 8
java
Copy code
import java.util.*;
public class OptionalExample {
public static void main(String[] args) {
Optional<String> name = Optional.of("John");
System.out.println(name.orElse("Default Name")); // Output:
John
name = Optional.empty();
System.out.println(name.orElse("Default Name")); // Output:
Default Name
}
}
Advanced Concepts
11. Implement a Singleton Pattern
java
Copy code
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
12. Implement a Basic LinkedList
java
Copy code
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
void append(int data) {
if (head == null) {
head = new Node(data);
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = new Node(data);
}
}
void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.append(1);
list.append(2);
list.append(3);
list.printList(); // Output: 1 2 3
}
}
13. Find the Intersection of Two Arrays
java
Copy code
import java.util.*;
public class ArrayIntersection {
public static void main(String[] args) {
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {4, 5, 6, 7, 8};
Set<Integer> set1 = new HashSet<>();
for (int num : array1) {
set1.add(num);
}
Set<Integer> intersection = new HashSet<>();
for (int num : array2) {
if (set1.contains(num)) {
intersection.add(num);
}
}
System.out.println(intersection); // Output: [4, 5]
}
}
14. Sort a Map by Values
java
Copy code
import java.util.*;
import java.util.stream.*;
public class SortMap {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("John", 25);
map.put("Jane", 30);
map.put("Alex", 20);
Map<String, Integer> sortedMap = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
System.out.println(sortedMap); // Output: {Alex=20, John=25,
Jane=30}
}
}
15. Implement a Basic Tree Structure
java
Copy code
class TreeNode {
int value;
TreeNode left, right;
TreeNode(int item) {
value = item;
left = right = null;
}
}
class BinaryTree {
TreeNode root;
void inorder(TreeNode node) {
if (node != null) {
inorder(node.left);
System.out.print(node.value + " ");
inorder(node.right);
}
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.root = new TreeNode(1);
tree.root.left = new TreeNode(2);
tree.root.right = new TreeNode(3);
tree.root.left.left = new TreeNode(4);
tree.root.left.right = new TreeNode(5);
tree.inorder(tree.root); // Output: 4 2 5 1 3
}
}
Additional Advanced Questions
16. Use Java Streams to Find Duplicate Elements in a List
java
Copy code
import java.util.*;
import java.util.stream.*;
public class FindDuplicates {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c", "a", "b",
"d");
Set<String> duplicates = list.stream()
.collect(Collectors.groupingBy(e -> e,
Collectors.counting()))
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
System.out.println(duplicates); // Output: [a, b]
}
}
17. Create a CompletableFuture Example
java
Copy code
import java.util.concurrent.CompletableFuture;
public class CompletableFutureExample {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> {
return "Hello";
}).thenApply(result -> {
return result + " World";
}).thenAccept(System.out::println); // Output: Hello World
}
}
18. Use Java 8 Optional with Default Values
java
Copy code
import java.util.Optional;
public class OptionalDefault {
public static void main(String[] args) {
Optional<String> optional = Optional.ofNullable(null);
String value = optional.orElse("Default Value");
System.out.println(value); // Output: Default Value
}
}
19. Create a Custom Functional Interface
java
Copy code
@FunctionalInterface
interface MyFunctionalInterface {
void execute(String message);
}
public class CustomFunctionalInterface {
public static void main(String[] args) {
MyFunctionalInterface myFunc = (message) -> {
System.out.println("Message: " + message);
};
myFunc.execute("Hello, Functional Interface!"); // Output:
Message: Hello, Functional Interface!
}
}
20. Convert a List to a Map Using Streams
java
Copy code
import java.util.*;
import java.util.stream.*;
public class ListToMap {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c");
Map<Integer, String> map = list.stream()
.collect(Collectors.toMap(String::length, s -> s));
System.out.println(map); // Output: {1=a, 2=b, 1=c}
}
}
Additional Questions
21. Remove Duplicates from a List
java
Copy code
import java.util.*;
public class RemoveDuplicates {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c", "a", "b");
Set<String> unique = new HashSet<>(list);
System.out.println(unique); // Output: [a, b, c]
}
}
22. Find the Intersection of Two Sets
java
Copy code
import java.util.*;
public class SetIntersection {
public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4,
5));
Set<Integer> set2 = new HashSet<>(Arrays.asList(4, 5, 6, 7,
8));
set1.retainAll(set2);
System.out.println(set1); // Output: [4, 5]
}
}
23. Find the Longest Common Prefix in an Array of Strings
java
Copy code
public class LongestCommonPrefix {
public static void main(String[] args) {
String[] strs = {"flower", "flow", "flight"};
if (strs == null || strs.length == 0) return;
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) return;
}
}
System.out.println(prefix); // Output: "fl"
}
}
24. Implement a Basic Queue
java
Copy code
import java.util.LinkedList;
public class BasicQueue {
private LinkedList<Integer> list = new LinkedList<>();
public void enqueue(int item) {
list.addLast(item);
}
public int dequeue() {
return list.removeFirst();
}
public boolean isEmpty() {
return list.isEmpty();
}
public static void main(String[] args) {
BasicQueue queue = new BasicQueue();
queue.enqueue(1);
queue.enqueue(2);
System.out.println(queue.dequeue()); // Output: 1
System.out.println(queue.dequeue()); // Output: 2
}
}
25. Calculate the GCD of Two Numbers
java
Copy code
public class GCD {
public static void main(String[] args) {
int a = 56, b = 98;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
System.out.println(a); // Output: 14
}
}
This list includes a variety of questions that should help you prepare for different aspects of a
Java interview. If you need more questions or specific topics, just let me know!
You said:
remaining 75
ChatGPT said:
ChatGPT
Sure! Here are 75 more coding questions with their answers using Java 8 or above:
Additional Java 8 Features and Functional Programming
26. Merge Two Lists into a Single List
java
Copy code
import java.util.*;
public class MergeLists {
public static void main(String[] args) {
List<String> list1 = Arrays.asList("a", "b", "c");
List<String> list2 = Arrays.asList("d", "e", "f");
List<String> mergedList = Stream.concat(list1.stream(),
list2.stream())
.collect(Collectors.toList());
System.out.println(mergedList); // Output: [a, b, c, d, e, f]
}
}
27. Generate a Range of Numbers Using Streams
java
Copy code
import java.util.stream.*;
public class RangeExample {
public static void main(String[] args) {
List<Integer> numbers = IntStream.range(1,
10).boxed().collect(Collectors.toList());
System.out.println(numbers); // Output: [1, 2, 3, 4, 5, 6, 7,
8, 9]
}
}
28. Group a List of Strings by Length
java
Copy code
import java.util.*;
import java.util.stream.*;
public class GroupByLength {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "bat", "banana",
"pear", "kiwi");
Map<Integer, List<String>> groupedByLength = words.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println(groupedByLength); // Output: {3=[bat],
4=[pear, kiwi], 5=[apple], 6=[banana]}
}
}
29. Find the Average of a List of Numbers
java
Copy code
import java.util.*;
import java.util.stream.*;
public class AverageExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
double average =
numbers.stream().mapToInt(Integer::intValue).average().orElse(0.0);
System.out.println(average); // Output: 3.0
}
}
30. Convert a List of Strings to Uppercase
java
Copy code
import java.util.*;
import java.util.stream.*;
public class ToUpperCase {
public static void main(String[] args) {
List<String> list = Arrays.asList("hello", "world");
List<String> upperCaseList =
list.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(upperCaseList); // Output: [HELLO, WORLD]
}
}
Collections and Data Structures
31. Implement a Stack
java
Copy code
import java.util.*;
public class StackExample {
private Deque<Integer> stack = new ArrayDeque<>();
public void push(int item) {
stack.push(item);
}
public int pop() {
return stack.pop();
}
public boolean isEmpty() {
return stack.isEmpty();
}
public static void main(String[] args) {
StackExample stack = new StackExample();
stack.push(1);
stack.push(2);
System.out.println(stack.pop()); // Output: 2
System.out.println(stack.pop()); // Output: 1
}
}
32. Implement a PriorityQueue
java
Copy code
import java.util.*;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(10);
pq.add(5);
pq.add(20);
System.out.println(pq.poll()); // Output: 5
System.out.println(pq.poll()); // Output: 10
}
}
33. Implement a HashMap and Iterate Over Its Entries
java
Copy code
import java.util.*;
public class HashMapExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " +
entry.getValue());
}
}
}
34. Find the First Non-Repeated Character in a String
java
Copy code
import java.util.*;
public class FirstNonRepeatedCharacter {
public static void main(String[] args) {
String str = "swiss";
Map<Character, Long> frequencyMap = str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c,
Collectors.counting()));
Character firstNonRepeated = str.chars()
.mapToObj(c -> (char) c)
.filter(c -> frequencyMap.get(c) == 1)
.findFirst()
.orElse(null);
System.out.println(firstNonRepeated); // Output: w
}
}
35. Sort a List of Custom Objects by a Property
java
Copy code
import java.util.*;
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + ": " + age;
}
}
public class SortObjects {
public static void main(String[] args) {
List<Person> people = Arrays.asList(new Person("Alice", 30),
new Person("Bob", 25), new Person("Charlie", 35));
people.sort(Comparator.comparingInt(p -> p.age));
people.forEach(System.out::println); // Output: Bob: 25,
Alice: 30, Charlie: 35
}
}
Algorithms
36. Binary Search Algorithm
java
Copy code
public class BinarySearch {
public static void main(String[] args) {
int[] array = {1, 3, 5, 7, 9};
int target = 7;
int result = binarySearch(array, target);
System.out.println(result); // Output: 3
}
public static int binarySearch(int[] array, int target) {
int left = 0, right = array.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (array[mid] == target) return mid;
if (array[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1; // Target not found
}
}
37. Merge Sort Algorithm
java
Copy code
import java.util.*;
public class MergeSort {
public static void main(String[] args) {
int[] array = {38, 27, 43, 3, 9, 82, 10};
mergeSort(array, 0, array.length - 1);
System.out.println(Arrays.toString(array)); // Output: [3, 9,
10, 27, 38, 43, 82]
}
public static void mergeSort(int[] array, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);
merge(array, left, mid, right);
}
}
public static void merge(int[] array, int left, int mid, int
right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int[] L = new int[n1];
int[] R = new int[n2];
System.arraycopy(array, left, L, 0, n1);
System.arraycopy(array, mid + 1, R, 0, n2);
int i = 0, j = 0;
int k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
array[k++] = L[i++];
} else {
array[k++] = R[j++];
}
}
while (i < n1) {
array[k++] = L[i++];
}
while (j < n2) {
array[k++] = R[j++];
}
}
}
38. Find the Kth Largest Element in an Array
java
Copy code
import java.util.*;
public class KthLargest {
public static void main(String[] args) {
int[] array = {3, 2, 1, 5, 6, 4};
int k = 2;
int result = findKthLargest(array, k);
System.out.println(result); // Output: 5
}
public static int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int num : nums) {
minHeap.add(num);
if (minHeap.size() > k) {
minHeap.poll();
}
}
return minHeap.peek();
}
}
39. Find the Longest Palindromic Substring
java
Copy code
public class LongestPalindromicSubstring {
public static void main(String[] args) {
String s = "babad";
String result = longestPalindrome(s);
System.out.println(result); // Output: "bab" or "aba"
}
public static String longestPalindrome(String s) {
if (s == null || s.length() == 0) return "";
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
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;
}
}
40. Implement Depth-First Search (DFS) on a Graph
java
Copy code
import java.util.*;
class Graph {
private final Map<Integer, List<Integer>> adjacencyList = new
HashMap<>();
public void addEdge(int src, int dest) {
adjacencyList.computeIfAbsent(src, k -> new
ArrayList<>()).add(dest);
}
public void dfs(int start) {
Set<Integer> visited = new HashSet<>();
dfsRecursive(start, visited);
}
private void dfsRecursive(int node, Set<Integer> visited) {
if (visited.contains(node)) return;
visited.add(node);
System.out.print(node + " ");
for (int neighbor : adjacencyList.getOrDefault(node,
Collections.emptyList())) {
dfsRecursive(neighbor, visited);
}
}
public static void main(String[] args) {
Graph graph = new Graph();
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 4);
graph.addEdge(2, 5);
graph.addEdge(3, 6);
graph.addEdge(3, 7);
graph.dfs(1); // Output: 1 2 4 5 3 6 7
}
}
Object-Oriented Programming
41. Implement an Abstract Class
java
Copy code
abstract class Animal {
abstract void makeSound();
void sleep() {
System.out.println("Zzz");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof");
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Woof
myDog.sleep(); // Output: Zzz
}
}
42. Implement an Interface
java
Copy code
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() {
System.out.println("Drawing a circle");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Drawable drawable = new Circle();
drawable.draw(); // Output: Drawing a circle
}
}
43. Use Inheritance to Extend a Class
java
Copy code
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Output: This animal eats food
dog.bark(); // Output: The dog barks
}
}
44. Create a Simple Java Bean
java
Copy code
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class JavaBeanExample {
public static void main(String[] args) {
Person person = new Person();
person.setName("Alice");
person.setAge(30);
System.out.println(person.getName() + " is " +
person.getAge() + " years old.");
// Output: Alice is 30 years old.
}
}
45. Override the toString() Method
java
Copy code
class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
@Override
public String toString() {
return "Book [title=" + title + ", author=" + author + "]";
}
}
public class ToStringExample {
public static void main(String[] args) {
Book book = new Book("1984", "George Orwell");
System.out.println(book); // Output: Book [title=1984,
author=George Orwell]
}
}
Concurrency and Multithreading
46. Create a Thread Using Runnable Interface
java
Copy code
public class RunnableExample {
public static void main(String[] args) {
Runnable task = () -> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + "
Value: " + i);
}
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
}
}
47. Use Callable and Future to Return a Result from a Thread
java
Copy code
import java.util.concurrent.*;
public class CallableExample {
public static void main(String[] args) throws
InterruptedException, ExecutionException {
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Integer> task = () -> {
Thread.sleep(1000);
return 123;
};
Future<Integer> future = executor.submit(task);
Integer result = future.get();
System.out.println(result); // Output: 123
executor.shutdown();
}
}
48. Synchronize Access to a Shared Resource
java
Copy code
public class SynchronizedExample {
private int counter = 0;
public synchronized void increment() {
counter++;
}
public static void main(String[] args) {
SynchronizedExample example = new SynchronizedExample();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(example.counter); // Output: 2000
}
}
49. Use CountDownLatch for Synchronization
java
Copy code
import java.util.concurrent.*;
public class CountDownLatchExample {
public static void main(String[] args) throws
InterruptedException {
CountDownLatch latch = new CountDownLatch(2);
Runnable task1 = () -> {
System.out.println("Task 1 is running");
latch.countDown();
};
Runnable task2 = () -> {
System.out.println("Task 2 is running");
latch.countDown();
};
new Thread(task1).start();
new Thread(task2).start();
latch.await();
System.out.println("All tasks are completed");
}
}
50. Use Semaphore for Managing Resource Access
java
Copy code
import java.util.concurrent.*;
public class SemaphoreExample {
public static void main(String[] args) throws
InterruptedException {
Semaphore semaphore = new Semaphore(1);
Runnable task = () -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() +
" acquired semaphore");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
System.out.println(Thread.currentThread().getName() +
" released semaphore");
}
};
new Thread(task).start();
new Thread(task).start();
}
}
Miscellaneous
51. Read and Write Files Using Files Class
java
Copy code
import java.nio.file.*;
import java.io.IOException;
public class FileIOExample {
public static void main(String[] args) {
String content = "Hello, World!";
Path path = Paths.get("example.txt");
try {
Files.write(path, content.getBytes());
String readContent = new
String(Files.readAllBytes(path));
System.out.println(readContent); // Output: Hello, World!
} catch (IOException e) {
e.printStackTrace();
}
}
}
52. Serialize and Deserialize an Object
java
Copy code
import java.io.*;
class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
public class SerializationExample {
public static void main(String[] args) {
Person person = new Person("Alice", 30);
try (ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("person.ser"))) {
out.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}
try (ObjectInputStream in = new ObjectInputStream(new
FileInputStream("person.ser"))) {
Person deserializedPerson = (Person) in.readObject();
System.out.println(deserializedPerson); // Output: Person
[name=Alice, age=30]
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
53. Implement a Simple Calculator
java
Copy code
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("Invalid operator");
return;
}
System.out.println("Result: " + result);
}
}
54. Implement a Basic Tic-Tac-Toe Game
java
Copy code
import java.util.Scanner;
public class TicTacToe {
private char[][] board = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ',
' ', ' '}};
private char currentPlayer = 'X';
public static void main(String[] args) {
TicTacToe game = new TicTacToe();
game.play();
}
private void play() {
while (true) {
printBoard();
makeMove();
if (isWinner()) {
printBoard();
System.out.println("Player " + currentPlayer + "
wins!");
return;
}
if (isBoardFull()) {
printBoard();
System.out.println("The game is a draw!");
return;
}
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
}
private void printBoard() {
System.out.println(" " + board[0][0] + " | " + board[0][1] +
" | " + board[0][2]);
System.out.println("-----------");
System.out.println(" " + board[1][0] + " | " + board[1][1] +
" | " + board[1][2]);
System.out.println("-----------");
System.out.println(" " + board[2][0] + " | " + board[2][1] +
" | " + board[2][2]);
}
private void makeMove() {
Scanner scanner = new Scanner(System.in);
int row, col;
while (true) {
System.out.print("Enter row (0, 1, 2) and column (0, 1,
2) for player " + currentPlayer + ": ");
row = scanner.nextInt();
col = scanner.nextInt();
if (row >= 0 && row < 3 && col >= 0 && col < 3 &&
board[row][col] == ' ') {
board[row][col] = currentPlayer;
break;
} else {
System.out.println("Invalid move. Try again.");
}
}
}
private boolean isBoardFull() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == ' ') {
return false;
}
}
}
return true;
}
private boolean isWinner() {
for (int i = 0; i < 3; i++) {
if (board[i][0] == currentPlayer && board[i][1] ==
currentPlayer && board[i][2] == currentPlayer) {
return true;
}
if (board[0][i] == currentPlayer && board[1][i] ==
currentPlayer && board[2][i] == currentPlayer) {
return true;
}
}
if (board[0][0] == currentPlayer && board[1][1] ==
currentPlayer && board[2][2] == currentPlayer) {
return true;
}
if (board[0][2] == currentPlayer && board[1][1] ==
currentPlayer && board[2][0] == currentPlayer) {
return true;
}
return false;
}
}
55. Use Regular Expressions to Validate an Email Address
java
Copy code
import java.util.regex.*;
public class EmailValidator {
public static void main(String[] args) {
String email = "
[email protected]";
String regex = "^[A-Za-z0-9+_.-]+@(.+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
boolean isValid = matcher.matches();
System.out.println("Is email valid? " + isValid); // Output:
Is email valid? true
}
}
56. Convert a String to a Date
java
Copy code
import java.text.*;
import java.util.*;
public class DateConversion {
public static void main(String[] args) throws ParseException {
String dateString = "2024-09-09";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(dateString);
System.out.println(date); // Output: Mon Sep 09 00:00:00 EDT
2024
}
}
57. Calculate the Factorial of a Number Using Recursion
java
Copy code
public class Factorial {
public static void main(String[] args) {
int num = 5;
System.out.println(factorial(num)); // Output: 120
}
public static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
}
58. Find the Fibonacci Sequence Up to a Given Number
java
Copy code
import java.util.*;
public class Fibonacci {
public static void main(String[] args) {
int count = 10;
List<Integer> fibonacciSequence = fibonacci(count);
System.out.println(fibonacciSequence); // Output: [0, 1, 1,
2, 3, 5, 8, 13, 21, 34]
}
public static List<Integer> fibonacci(int count) {
List<Integer> sequence = new ArrayList<>();
int a = 0, b = 1;
while (count-- > 0) {
sequence.add(a);
int next = a + b;
a = b;
b = next;
}
return sequence;
}
}
59. Find the Greatest Common Divisor (GCD) of Two Numbers Using Euclid's
Algorithm
java
Copy code
public class GCD {
public static void main(String[] args) {
int a = 56;
int b = 98;
int gcd = findGCD(a, b);
System.out.println(gcd); // Output: 14
}
public static int findGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
60. Generate a Random Number Between 1 and 100
java
Copy code
import java.util.Random;
public class RandomNumber {
public static void main(String[] args) {
Random random = new Random();
int number = random.nextInt(100) + 1;
System.out.println(number); // Output: A random number
between 1 and 100
}
}
More Algorithms
61. Implement Quick Sort Algorithm
java
Copy code
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] array = {10, 7, 8, 9, 1, 5};
quickSort(array, 0, array.length - 1);
System.out.println(Arrays.toString(array)); // Output: [1, 5,
7, 8, 9, 10]
}
public static void quickSort(int[] array, int low, int high) {
if (low < high) {
int pi = partition(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}
private static int partition(int[] array, int low, int high) {
int pivot = array[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {
i++;
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
int temp = array[i + 1];
array[i + 1] = array[high];
array[high] = temp;
return i + 1;
}
}
62. Implement Merge Sort Algorithm
java
Copy code
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] array = {12, 11, 13, 5, 6, 7};
mergeSort(array, 0, array.length - 1);
System.out.println(Arrays.toString(array)); // Output: [5, 6,
7, 11, 12, 13]
}
public static void mergeSort(int[] array, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);
merge(array, left, mid, right);
}
}
private static void merge(int[] array, int left, int mid, int
right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int[] leftArray = new int[n1];
int[] rightArray = new int[n2];
System.arraycopy(array, left, leftArray, 0, n1);
System.arraycopy(array, mid + 1, rightArray, 0, n2);
int i = 0, j = 0;
int k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
array[k++] = leftArray[i++];
} else {
array[k++] = rightArray[j++];
}
}
while (i < n1) {
array[k++] = leftArray[i++];
}
while (j < n2) {
array[k++] = rightArray[j++];
}
}
}
63. Implement Dijkstra's Algorithm for Shortest Path
java
Copy code
import java.util.*;
public class DijkstraAlgorithm {
private static final int INF = Integer.MAX_VALUE;
public static void main(String[] args) {
int[][] graph = {
{0, 7, INF, INF, INF, 14},
{7, 0, 9, INF, INF, 10},
{INF, 9, 0, 6, INF, INF},
{INF, INF, 6, 0, 8, 15},
{INF, INF, INF, 8, 0, 9},
{14, 10, INF, 15, 9, 0}
};
dijkstra(graph, 0);
}
public static void dijkstra(int[][] graph, int src) {
int V = graph.length;
int[] dist = new int[V];
boolean[] sptSet = new boolean[V];
Arrays.fill(dist, INF);
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++) {
if (!sptSet[v] && graph[u][v] != INF && dist[u] !=
INF && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
printSolution(dist);
}
private static int minDistance(int[] dist, boolean[] sptSet) {
int min = INF, minIndex = -1;
for (int v = 0; v < dist.length; v++) {
if (!sptSet[v] && dist[v] <= min) {
min = dist[v];
minIndex = v;
}
}
return minIndex;
}
private static void printSolution(int[] dist) {
System.out.println("Vertex \t Distance from Source");
for (int i = 0; i < dist.length; i++) {
System.out.println(i + " \t " + dist[i]);
}
}
}
64. Implement the A Algorithm for Shortest Path*
java
Copy code
import java.util.*;
class Node {
int x, y;
int gCost, hCost;
Node parent;
Node(int x, int y) {
this.x = x;
this.y = y;
this.gCost = Integer.MAX_VALUE;
this.hCost = 0;
this.parent = null;
}
int fCost() {
return gCost + hCost;
}
}
public class AStarAlgorithm {
private static final int[][] directions = {{0, 1}, {1, 0}, {0, -
1}, {-1, 0}};
private static final int GRID_SIZE = 5;
public static void main(String[] args) {
Node[][] grid = new Node[GRID_SIZE][GRID_SIZE];
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = 0; j < GRID_SIZE; j++) {
grid[i][j] = new Node(i, j);
}
}
Node start = grid[0][0];
Node goal = grid[4][4];
findPath(grid, start, goal);
}
public static void findPath(Node[][] grid, Node start, Node goal)
{
PriorityQueue<Node> openSet = new
PriorityQueue<>(Comparator.comparingInt(Node::fCost));
Set<Node> closedSet = new HashSet<>();
start.gCost = 0;
start.hCost = heuristic(start, goal);
openSet.add(start);
while (!openSet.isEmpty()) {
Node current = openSet.poll();
if (current == goal) {
reconstructPath(current);
return;
}
closedSet.add(current);
for (int[] dir : directions) {
int newX = current.x + dir[0];
int newY = current.y + dir[1];
if (isValid(newX, newY)) {
Node neighbor = grid[newX][newY];
if (closedSet.contains(neighbor)) continue;
int tentativeGCost = current.gCost + 1;
if (tentativeGCost < neighbor.gCost) {
neighbor.gCost = tentativeGCost;
neighbor.hCost = heuristic(neighbor, goal);
neighbor.parent = current;
if (!openSet.contains(neighbor)) {
openSet.add(neighbor);
}
}
}
}
}
}
private static boolean isValid(int x, int y) {
return x >= 0 && y >= 0 && x < GRID_SIZE && y < GRID_SIZE;
}
private static int heuristic(Node a, Node b) {
return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
}
private static void reconstructPath(Node node) {
List<Node> path = new ArrayList<>();
while (node != null) {
path.add(node);
node = node.parent;
}
Collections.reverse(path);
for (Node n : path) {
System.out.println("[" + n.x + "," + n.y + "]");
}
}
}
65. Implement the Knapsack Problem Using Dynamic Programming
java
Copy code
public class Knapsack {
public static void main(String[] args) {
int[] weights = {1, 2, 3};
int[] values = {60, 100, 120};
int capacity = 5;
int n = values.length;
int maxValue = knapsack(weights, values, n, capacity);
System.out.println("Maximum value: " + maxValue); // Output:
220
}
public static int knapsack(int[] weights, int[] values, int n,
int capacity) {
int[][] dp = new int[n + 1][capacity + 1];
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= capacity; w++) {
if (i == 0 || w == 0) {
dp[i][w] = 0;
} else if (weights[i - 1] <= w) {
dp[i][w] = Math.max(values[i - 1] + dp[i - 1][w -
weights[i - 1]], dp[i - 1][w]);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}
return dp[n][capacity];
}
}
This should give you a comprehensive overview of Java programming basics, algorithms, and
more advanced topics. Feel free to ask if you need more details on any specific topic!
You said:
mostly aksing string and array related questions..
ChatGPT said:
ChatGPT
Got it! Here are some more Java coding questions specifically related to strings and arrays:
String-Related Questions
66. Reverse a String
java
Copy code
public class ReverseString {
public static void main(String[] args) {
String str = "hello";
String reversed = new
StringBuilder(str).reverse().toString();
System.out.println(reversed); // Output: "olleh"
}
}
67. Check if a String is a Palindrome
java
Copy code
public class Palindrome {
public static void main(String[] args) {
String str = "madam";
boolean isPalindrome = str.equals(new
StringBuilder(str).reverse().toString());
System.out.println(isPalindrome); // Output: true
}
}
68. Find the First Non-Repeating Character in a String
java
Copy code
import java.util.*;
public class FirstNonRepeatingChar {
public static void main(String[] args) {
String str = "swiss";
char result = findFirstNonRepeatingChar(str);
System.out.println(result); // Output: 'w'
}
public static char findFirstNonRepeatingChar(String str) {
Map<Character, Integer> countMap = new LinkedHashMap<>();
for (char c : str.toCharArray()) {
countMap.put(c, countMap.getOrDefault(c, 0) + 1);
}
for (Map.Entry<Character, Integer> entry :
countMap.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return '\0'; // No non-repeating character
}
}
69. Remove Duplicates from a String
java
Copy code
public class RemoveDuplicates {
public static void main(String[] args) {
String str = "aabbcc";
StringBuilder result = new StringBuilder();
Set<Character> seen = new HashSet<>();
for (char c : str.toCharArray()) {
if (seen.add(c)) {
result.append(c);
}
}
System.out.println(result.toString()); // Output: "abc"
}
}
70. Count the Number of Vowels in a String
java
Copy code
public class CountVowels {
public static void main(String[] args) {
String str = "hello world";
int count = countVowels(str);
System.out.println(count); // Output: 3
}
public static int countVowels(String str) {
int count = 0;
for (char c : str.toLowerCase().toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c ==
'u') {
count++;
}
}
return count;
}
}
71. Find the Longest Substring Without Repeating Characters
java
Copy code
import java.util.*;
public class LongestSubstringWithoutRepeating {
public static void main(String[] args) {
String str = "abcabcbb";
int length = lengthOfLongestSubstring(str);
System.out.println(length); // Output: 3
}
public static int lengthOfLongestSubstring(String s) {
Set<Character> set = new HashSet<>();
int left = 0, maxLength = 0;
for (int right = 0; right < s.length(); right++) {
while (set.contains(s.charAt(right))) {
set.remove(s.charAt(left++));
}
set.add(s.charAt(right));
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
}
72. Convert a String to an Integer
java
Copy code
public class StringToInteger {
public static void main(String[] args) {
String str = "1234";
int number = Integer.parseInt(str);
System.out.println(number); // Output: 1234
}
}
73. Check if Two Strings are Anagrams
java
Copy code
import java.util.*;
public class Anagram {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
boolean isAnagram = areAnagrams(str1, str2);
System.out.println(isAnagram); // Output: true
}
public static boolean areAnagrams(String s1, String s2) {
if (s1.length() != s2.length()) return false;
char[] arr1 = s1.toCharArray();
char[] arr2 = s2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
}
74. Find All Occurrences of a Substring in a String
java
Copy code
import java.util.*;
public class FindOccurrences {
public static void main(String[] args) {
String str = "ABABABAB";
String subStr = "AB";
List<Integer> indices = findAllOccurrences(str, subStr);
System.out.println(indices); // Output: [0, 2, 4, 6]
}
public static List<Integer> findAllOccurrences(String str, String
subStr) {
List<Integer> indices = new ArrayList<>();
int index = str.indexOf(subStr);
while (index >= 0) {
indices.add(index);
index = str.indexOf(subStr, index + 1);
}
return indices;
}
}
Array-Related Questions
75. Find the Maximum Element in an Array
java
Copy code
public class MaxElement {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9};
int max = findMax(arr);
System.out.println(max); // Output: 9
}
public static int findMax(int[] arr) {
int max = arr[0];
for (int num : arr) {
if (num > max) {
max = num;
}
}
return max;
}
}
76. Find the Minimum Element in an Array
java
Copy code
public class MinElement {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9};
int min = findMin(arr);
System.out.println(min); // Output: 1
}
public static int findMin(int[] arr) {
int min = arr[0];
for (int num : arr) {
if (num < min) {
min = num;
}
}
return min;
}
}
77. Find the Average of Array Elements
java
Copy code
public class AverageArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
double average = findAverage(arr);
System.out.println(average); // Output: 3.0
}
public static double findAverage(int[] arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
return (double) sum / arr.length;
}
}
78. Check if an Array Contains a Specific Element
java
Copy code
public class ContainsElement {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int target = 3;
boolean contains = containsElement(arr, target);
System.out.println(contains); // Output: true
}
public static boolean containsElement(int[] arr, int target) {
for (int num : arr) {
if (num == target) {
return true;
}
}
return false;
}
}
79. Find the Intersection of Two Arrays
java
Copy code
import java.util.*;
public class ArrayIntersection {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {4, 5, 6, 7, 8};
int[] intersection = findIntersection(arr1, arr2);
System.out.println(Arrays.toString(intersection)); // Output:
[4, 5]
}
public static int[] findIntersection(int[] arr1, int[] arr2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> intersection = new HashSet<>();
for (int num : arr1) {
set1.add(num);
}
for (int num : arr2) {
if (set1.contains(num)) {
intersection.add(num);
}
}
return
intersection.stream().mapToInt(Integer::intValue).toArray();
}
}
80. Merge Two Sorted Arrays
java
Copy code
import java.util.Arrays;
public class MergeSortedArrays {
public static void main(String[] args) {
int[] arr1 = {1, 3, 5};
int[] arr2 = {2, 4, 6};
int[] merged = mergeArrays(arr1, arr2);
System.out.println(Arrays.toString(merged
)); // Output: [1, 2, 3, 4, 5, 6] }
css
Copy code
public static int[] mergeArrays(int[] arr1, int[] arr2) {
int[] merged = new int[arr1.length + arr2.length];
int i = 0, j = 0, k = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
while (i < arr1.length) {
merged[k++] = arr1[i++];
}
while (j < arr2.length) {
merged[k++] = arr2[j++];
}
return merged;
}
}
```
81. Rotate an Array by k Positions ```java import java.util.Arrays;
arduino
Copy code
public class RotateArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int k = 2;
rotateArray(arr, k);
System.out.println(Arrays.toString(arr)); // Output: [4, 5, 1, 2,
3]
}
public static void rotateArray(int[] arr, int k) {
k = k % arr.length;
reverse(arr, 0, arr.length - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, arr.length - 1);
}
private static void reverse(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
}
```
82. Find the Kth Largest Element in an Array ```java import java.util.Arrays; import
java.util.Collections; import java.util.PriorityQueue;
arduino
Copy code
public class KthLargestElement {
public static void main(String[] args) {
int[] arr = {3, 2, 1, 5, 6, 4};
int k = 2;
int kthLargest = findKthLargest(arr, k);
System.out.println(kthLargest); // Output: 5
}
public static int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);
for (int num : nums) {
minHeap.offer(num);
if (minHeap.size() > k) {
minHeap.poll();
}
}
return minHeap.peek();
}
}
```
83. Find the Majority Element in an Array ```java import java.util.HashMap; import
java.util.Map;
csharp
Copy code
public class MajorityElement {
public static void main(String[] args) {
int[] nums = {3, 2, 3};
int majority = findMajorityElement(nums);
System.out.println(majority); // Output: 3
}
public static int findMajorityElement(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : nums) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
if (countMap.get(num) > nums.length / 2) {
return num;
}
}
throw new IllegalArgumentException("No majority element");
}
}
```
84. Find the Missing Number in an Array ```java public class MissingNumber { public
static void main(String[] args) { int[] nums = {3, 0, 1}; int missingNumber =
findMissingNumber(nums); System.out.println(missingNumber); // Output: 2 }
arduino
Copy code
public static int findMissingNumber(int[] nums) {
int n = nums.length;
int sum = (n * (n + 1)) / 2;
for (int num : nums) {
sum -= num;
}
return sum;
}
}
```
85. Find the Duplicates in an Array ```java import java.util.HashSet; import java.util.Set;
csharp
Copy code
public class FindDuplicates {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 2, 3};
Set<Integer> duplicates = findDuplicates(nums);
System.out.println(duplicates); // Output: [2, 3]
}
public static Set<Integer> findDuplicates(int[] nums) {
Set<Integer> set = new HashSet<>();
Set<Integer> duplicates = new HashSet<>();
for (int num : nums) {
if (!set.add(num)) {
duplicates.add(num);
}
}
return duplicates;
}
}
```
86. Find the Longest Consecutive Sequence ```java import java.util.Arrays; import
java.util.HashSet; import java.util.Set;
csharp
Copy code
public class LongestConsecutiveSequence {
public static void main(String[] args) {
int[] nums = {100, 4, 200, 1, 3, 2};
int longest = longestConsecutive(nums);
System.out.println(longest); // Output: 4
}
public static int longestConsecutive(int[] nums) {
Set<Integer> numSet = new HashSet<>();
for (int num : nums) {
numSet.add(num);
}
int longestStreak = 0;
for (int num : numSet) {
if (!numSet.contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;
while (numSet.contains(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
}
```
87. Find the Peak Element in an Array ```java public class PeakElement { public static
void main(String[] args) { int[] nums = {1, 2, 3, 1}; int peakIndex = findPeakElement(nums);
System.out.println(peakIndex); // Output: 2 }
css
Copy code
public static int findPeakElement(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if ((i == 0 || nums[i] > nums[i - 1]) &&
(i == nums.length - 1 || nums[i] > nums[i + 1])) {
return i;
}
}
return -1; // Should not be reached
}
}
```
88. Move Zeros to the End of an Array ```java import java.util.Arrays;
arduino
Copy code
public class MoveZeros {
public static void main(String[] args) {
int[] arr = {0, 1, 0, 3, 12};
moveZeroes(arr);
System.out.println(Arrays.toString(arr)); // Output: [1, 3, 12, 0,
0]
}
public static void moveZeroes(int[] arr) {
int nonZeroIndex = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
arr[nonZeroIndex++] = arr[i];
}
}
while (nonZeroIndex < arr.length) {
arr[nonZeroIndex++] = 0;
}
}
}
```
89. Find the Common Elements in Three Sorted Arrays ```java import java.util.ArrayList;
import java.util.Arrays; import java.util.List;
csharp
Copy code
public class CommonElementsInThreeArrays {
public static void main(String[] args) {
int[] arr1 = {1, 5, 10, 20, 40};
int[] arr2 = {6, 7, 20, 80, 100};
int[] arr3 = {3, 4, 15, 20, 30};
List<Integer> commonElements = findCommonElements(arr1, arr2,
arr3);
System.out.println(commonElements); // Output: [20]
}
public static List<Integer> findCommonElements(int[] arr1, int[] arr2,
int[] arr3) {
List<Integer> common = new ArrayList<>();
int i = 0, j = 0, k = 0;
while (i < arr1.length && j < arr2.length && k < arr3.length) {
if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
common.add(arr1[i]);
i++;
j++;
k++;
} else if (arr1[i] < arr2[j]) {
i++;
} else if (arr2[j] < arr3[k]) {
j++;
} else {
k++;
}
}
return common;
}
}
```
90. Find the Smallest Subarray with Sum Greater than or Equal to a Given Value
```java public class SmallestSubarraySum { public static void main(String[] args) { int[] arr =
{1, 4, 4}; int s = 8; int minLength = findMinSubarrayLength(arr, s);
System.out.println(minLength); // Output: 3 }
sql
Copy code
public static int findMinSubarrayLength(int[] arr, int s) {
int minLength = Integer.MAX_VALUE;
int sum = 0, start = 0;
for (int end = 0; end < arr.length; end++) {
sum += arr[end];
while (sum >= s) {
minLength = Math.min(minLength, end - start + 1);
sum -= arr[start++];
}
}
return minLength == Integer.MAX_VALUE ? 0 : minLength;
}
}
```
91. Find All Unique Triplets in an Array that Sum to Zero ```java import
java.util.ArrayList; import java.util.Arrays; import java.util.List;
css
Copy code
public class ThreeSum {
public static void main(String[] args) {
int[] nums = {-1, 0, 1, 2, -1, -4};
List<List<Integer>> triplets = threeSum(nums);
System.out.println(triplets); // Output: [[-1, -1, 2], [-1, 0, 1]]
}
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue; // Skip
duplicates
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.add(Arrays.asList(nums[i], nums[left],
nums[right]));
while (left < right && nums[left] == nums[left + 1])
left++; // Skip duplicates
while (left < right && nums[right] == nums[right - 1])
right--; // Skip duplicates
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
}
```
92. Find the Longest Increasing Subsequence ```java import java.util.Arrays;
scss
Copy code
public class LongestIncreasingSubsequence {
public static void main(String[] args) {
int[] nums = {10, 9, 2, 5, 3, 7, 101, 18};
int length = lengthOfLIS(nums);
System.out.println(length); // Output: 4
}
public static int lengthOfLIS(int[] nums) {
if (nums.length == 0) return 0;
int[] dp = new int[nums.length];
Arrays.fill(dp, 1);
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
return Arrays.stream(dp).max().getAsInt();
}
}
```
93. Find the Sum of All Subarrays ```java public class SumOfSubarrays { public static void
main(String[] args) { int[] arr = {1, 2, 3}; int sum = findSumOfSubarrays(arr);
System.out.println(sum); // Output: 20 }
arduino
Copy code
public static int findSumOfSubarrays(int[] arr) {
int sum = 0;
int n = arr.length;
for (int i = 0; i < n; i++) {
sum += arr[i] * (i + 1) * (n - i);
}
return sum;
}
}
```
94. Find the Largest Sum Contiguous Subarray ```java public class
MaximumSubarraySum { public static void main(String[] args) { int[] nums = {-2, 1, -3, 4, -
1, 2, 1, -5, 4}; int maxSum = maxSubArray(nums); System.out.println(maxSum); // Output: 6
}
arduino
Copy code
public static int maxSubArray(int[] nums) {
int maxSum = nums[0];
int currentSum = nums[0];
for (int i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
}
```
95. Find the Kth Smallest Element in an Array ```java import java.util.PriorityQueue;
arduino
Copy code
public class KthSmallestElement {
public static void main(String[] args) {
int[] nums = {3, 2, 1, 5, 6, 4};
int k = 2;
int kthSmallest = findKthSmallest(nums, k);
System.out.println(kthSmallest); // Output: 2
}
public static int findKthSmallest(int[] nums, int k) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b -
a);
for (int num : nums) {
maxHeap.offer(num);
if (maxHeap.size() > k) {
maxHeap.poll();
}
}
return maxHeap.peek();
}
}
```
96. Find the Union of Two Arrays ```java import java.util.Arrays; import java.util.Set;
import java.util.HashSet;
csharp
Copy code
public class UnionOfArrays {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4};
int[] arr2 = {3, 4, 5, 6};
int[] union = findUnion(arr1, arr2);
System.out.println(Arrays.toString(union)); // Output: [1, 2, 3, 4,
5, 6]
}
public static int[] findUnion(int[] arr1, int[] arr2) {
Set<Integer> set = new HashSet<>();
for (int num : arr1) {
set.add(num);
}
for (int num : arr2) {
set.add(num);
}
return set.stream().mapToInt(Integer::intValue).toArray();
}
}
```
97. Find the Largest Product of Two Numbers in an Array ```java import java.util.Arrays;
arduino
Copy code
public class LargestProduct {
public static void main(String[] args) {
int[] nums = {3, 6, 1, 9, 4};
int product = maxProduct(nums);
System.out.println(product); // Output: 54
}
public static int maxProduct(int[] nums) {
Arrays.sort(nums);
return nums[nums.length - 1] * nums[nums.length - 2];
}
}
```
98. Find the Missing and Repeating Numbers in an Array ```java import java.util.Arrays;
css
Copy code
public class MissingAndRepeating {
public static void main(String[] args) {
int[] nums = {1, 2, 2, 4};
int[] result = findMissingAndRepeating(nums);
System.out.println(Arrays.toString(result)); // Output: [2, 3]
}
public static int[] findMissingAndRepeating(int[] nums) {
int n = nums.length;
int[] result = new int[2]; // result[0] is repeating, result[1] is
missing
int[] count = new int[n + 1];
for (int num : nums) {
count[num]++;
}
for (int i = 1; i <= n; i++) {
if (count[i] == 2) {
result[0] = i;
} else if (count[i] == 0) {
result[1] = i;
}
}
return result;
}
}
```
99. Find the Sum of Elements in a Subarray with a Given Length ```java public class
SumOfSubarray { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int k = 3;
int sum = findSumOfSubarray(arr, k); System.out.println(sum); // Output: 12 }
arduino
Copy code
public static int findSumOfSubarray(int[] arr, int k) {
int maxSum = 0, windowSum = 0;
for (int i = 0; i < arr.length; i++) {
windowSum += arr[i];
if (i >= k - 1) {
maxSum = Math.max(maxSum, windowSum);
windowSum -= arr[i - k + 1];
}
}
return maxSum;
}
}
```
100. Find the Longest Palindromic Substring ```java public class
LongestPalindromicSubstring { public static void main(String[] args) { String s = "babad";
String longestPalindromicSubstring = longestPalindrome(s);
System.out.println(longestPalindromicSubstring); // Output: "bab" or "aba" }
sql
Copy code
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);
int len2 = expandAroundCenter(s, i, i + 1);
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;
}
}
```
These solutions cover a wide range of array-related problems and should give you a good
understanding of various algorithms and techniques. Let me know if you have any specific
questions or need further explanations!
Messages beyond this point are only visible to you
O
ChatGPT can make mistakes. Check important info.