HACKATHON-DSA
Problem-1 : Most Frequent Element
Solution:
// Most Frequent Element
import java.util.*;
public class first {
public static int mostFrequentElement(int[] arr) {
Map<Integer, Integer> frequencyMap = new HashMap<>();
// Count the frequency of each element in the array
for (int num : arr) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
int maxFrequency = 0;
int mostFrequentElement = -1;
// Find the element with the maximum frequency
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
int currentFrequency = entry.getValue();
if (currentFrequency > maxFrequency) {
maxFrequency = currentFrequency;
mostFrequentElement = entry.getKey();
}
}
return mostFrequentElement;
}
public static void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println(mostFrequentElement(arr));
}
}
Problem-2 : Check whether an Undirected Graph is a Tree or not
Solution:
// Check Whether an Undirected Graph is a Tree or Not
import java.util.*;
public class second {
private int vertexCount;
private static LinkedList<Integer> adj[];
second(int vertexCount) {
this.vertexCount = vertexCount;
this.adj = new LinkedList[vertexCount];
for (int i = 0; i < vertexCount; ++i) {
adj[i] = new LinkedList<Integer>();
}
}
public void addEdge(int v, int w) {
if (!isValidIndex(v) || !isValidIndex(w)) {
return;
}
adj[v].add(w);
adj[w].add(v);
}
private boolean isValidIndex(int i) {
return i >= 0 && i < vertexCount;
}
private boolean isCyclic(int v, boolean visited[], int parent) {
visited[v] = true;
for (int neighbor : adj[v]) {
if (!visited[neighbor]) {
if (isCyclic(neighbor, visited, v)) {
return true;
}
} else if (neighbor != parent) {
return true;
}
}
return false;
}
public boolean isTree() {
boolean[] visited = new boolean[vertexCount];
// Check for cycles starting from each unvisited node
for (int i = 0; i < vertexCount; i++) {
if (!visited[i] && isCyclic(i, visited, -1)) {
return false;
}
}
// Check for connectedness
for (int i = 0; i < vertexCount; i++) {
if (!visited[i]) {
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
// Get the number of nodes from the input.
int noOfNodes = sc.nextInt();
// Get the number of edges from the input.
int noOfEdges = sc.nextInt();
second graph = new second(noOfNodes);
// Adding edges to the graph
for (int i = 0; i < noOfEdges; ++i) {
graph.addEdge(sc.nextInt(), sc.nextInt());
}
if (graph.isTree()) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
Problem-3 : Sort Nearly Sorted Array
Solution:
// Sort Nearly Sorted Array
import java.util.*;
public class third {
private static void sortArray(int[] arr, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
// Build the initial min heap with the first k+1 elements
for (int i = 0; i <= k; i++) {
minHeap.offer(arr[i]);
}
int index = 0;
// Continue adding elements to the min heap and poll the minimum
// element to maintain the nearly sorted property
for (int i = k + 1; i < arr.length; i++) {
arr[index++] = minHeap.poll();
minHeap.offer(arr[i]);
}
// Empty the remaining elements from the min heap
while (!minHeap.isEmpty()) {
arr[index++] = minHeap.poll();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input size of the array
int n = sc.nextInt();
// Input maximum number of steps
int k = sc.nextInt();
// Input elements of the k-sorted array
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// Sort the k-sorted array
sortArray(arr, k);
// Print the sorted array
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Problem-4: Find Sum between pth and qth Smallest Elements
Solution:
// Find Sum Between pth and qth Smallest Elements
import java.util.*;
public class fourth {
public static int sumBetweenPthToQthSmallestElement(int[] arr, int p, int
q) {
Arrays.sort(arr);
int sum = 0;
for (int i = p - 1; i < q; i++) {
sum += arr[i];
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int p = sc.nextInt();
int q = sc.nextInt();
System.out.println(sumBetweenPthToQthSmallestElement(arr, p, q));
}
}
Problem-5: Find all Symmetric Pairs in an Array
Solution:
//Find All Symmetric Pairs in an Array
import java.util.*;
public class fifth {
public static void main(String[] args) {
int[][] arr = {{1, 2}, {2, 1}, {3, 4}, {4, 3}};
findSymmetricPairs(arr);
}
public static void findSymmetricPairs(int[][] arr) {
// Create a HashMap to store pairs as (b, a)
HashMap<String, String> pairs = new HashMap<>();
// Find all symmetric pairs
ArrayList<int[]> symmetricPairs = new ArrayList<>();
for (int[] pair : arr) {
String key = pair[0] + " " + pair[1];
if (pairs.containsKey(key)) {
symmetricPairs.add(pair);
} else {
pairs.put(key, "");
}
}
// Print the symmetric pairs
for (int[] pair : symmetricPairs) {
System.out.println(Arrays.toString(pair));
}
}
}
Problem-6 :Find all common element in all rows of matrix
Solution:
//Find All Common Element in All Rows of Matrix
import java.util.*;
public class sixth {
public static void printElementInAllRows(int mat[][]) {
int row = mat.length;
int col = mat[0].length;
Map<Integer, Integer> elementCount = new HashMap<>();
// Count occurrences of each element in the first row
for (int j = 0; j < col; j++) {
int element = mat[0][j];
elementCount.put(element, elementCount.getOrDefault(element, 0) +
1);
}
// Check common elements in each row
for (int i = 1; i < row; i++) {
Map<Integer, Integer> currentRowCount = new HashMap<>();
// Count occurrences of each element in the current row
for (int j = 0; j < col; j++) {
int element = mat[i][j];
currentRowCount.put(element,
currentRowCount.getOrDefault(element, 0) + 1);
}
// Update elementCount with common elements in the current row
List<Integer> commonElements = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry :
currentRowCount.entrySet()) {
int element = entry.getKey();
int count = entry.getValue();
if (elementCount.containsKey(element)) {
int minCount = Math.min(count,
elementCount.get(element));
for (int k = 0; k < minCount; k++) {
commonElements.add(element);
}
}
}
// Update elementCount with the common elements in the current
row
elementCount.clear();
for (int element : commonElements) {
elementCount.put(element, elementCount.getOrDefault(element,
0) + 1);
}
}
// Print common elements in ascending order
List<Integer> result = new ArrayList<>(elementCount.keySet());
Collections.sort(result);
for (int element : result) {
System.out.print(element + " ");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int col = sc.nextInt();
int matrix[][] = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
matrix[i][j] = sc.nextInt();
}
}
printElementInAllRows(matrix);
}
}
Problem-7: Find itinerary in order
Solution:
//Find Itinerary in Order
import java.util.*;
public class seventh {
public static void findItinerary(Map<String, String> tickets) {
HashMap<String, Boolean> isSource = new HashMap<>();
// Create a map to check whether a city is a source or destination
for (Map.Entry<String, String> entry : tickets.entrySet()) {
isSource.put(entry.getKey(), true);
isSource.put(entry.getValue(), false);
}
// Find the starting city
String startCity = null;
for (Map.Entry<String, Boolean> entry : isSource.entrySet()) {
if (entry.getValue()) {
startCity = entry.getKey();
break;
}
}
// Check if startCity is null
if (startCity == null) {
System.out.println("Invalid Input");
return;
}
// Print the itinerary
while (tickets.containsKey(startCity)) {
String destination = tickets.get(startCity);
System.out.println(startCity + "->" + destination);
startCity = destination;
}
}
public static void main(String[] args) {
Map<String, String> tickets = new HashMap<>();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
tickets.put(sc.next(), sc.next());
}
findItinerary(tickets);
}
}
Problem-8: Search element in a rotated array
Solution:
// Search Element in a Rotated Array
import java.util.*;
public class eigth {
public static int search(int arr[], int left, int right, int key) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) {
return mid;
}
// Check if the left half is sorted
if (arr[left] <= arr[mid]) {
// Check if the key is in the left half
if (arr[left] <= key && key < arr[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
// Check if the right half is sorted
else {
// Check if the key is in the right half
if (arr[mid] < key && key <= arr[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1; // Key not found
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int key = sc.nextInt();
int result = search(arr, 0, n - 1, key);
if (result != -1) {
System.out.println(result);
} else {
System.out.println("-1");
}
}
}
Problem-9: Find median after merging two sorted arrays
Solution:
//Find Median After Merging Two Sorted Arrays
import java.util.*;
public class ninth {
public static int median(int[] arr1, int[] arr2, int n) {
int[] mergedArr = new int[2 * n];
int i = 0, j = 0, k = 0;
while (i < n && j < n) {
if (arr1[i] < arr2[j]) {
mergedArr[k++] = arr1[i++];
} else {
mergedArr[k++] = arr2[j++];
}
}
// Copy the remaining elements from arr1, if any
while (i < n) {
mergedArr[k++] = arr1[i++];
}
// Copy the remaining elements from arr2, if any
while (j < n) {
mergedArr[k++] = arr2[j++];
}
// Calculate the median
return (mergedArr[n - 1] + mergedArr[n]) / 2;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr1[] = new int[n];
int arr2[] = new int[n];
for (int i = 0; i < n; i++) {
arr1[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
arr2[i] = sc.nextInt();
}
System.out.println(median(arr1, arr2, n));
}
}