0% found this document useful (0 votes)
57 views37 pages

Dsa Assignment

The document contains code snippets and questions related to finding the median after merging two sorted arrays. The code provided defines a method to find the median after merging two sorted arrays of lengths n and m. It uses a binary search approach on the merged array to find the median in O(log(n+m)) time complexity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views37 pages

Dsa Assignment

The document contains code snippets and questions related to finding the median after merging two sorted arrays. The code provided defines a method to find the median after merging two sorted arrays of lengths n and m. It uses a binary search approach on the merged array to find the median in O(log(n+m)) time complexity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Question :1

Most Frequent Element


import java.util.*;

public class Source {

public static int mostFrequentElement(int[] arr,int n) {


Arrays.sort(arr);

// find the max frequency using linear


// traversal
int max_count = 1, reserve = arr[0];
int curr_count = 1;

for (int i = 1; i < n; i++)


{
if (arr[i] == arr[i - 1])
curr_count++;

else
{
if (curr_count > max_count)
{

max_count = curr_count;
reserve = arr[i - 1];
}
curr_count = 1;
}
}

if (curr_count > max_count)

{
max_count = curr_count;
reserve= arr[n - 1];
}

return reserve;

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,n));

}
}
Question : 2

Check Whether an
Undirected Graph is a Tree
or Not
import java.util.*;

public class Source {

private int vertexCount;


private static LinkedList<Integer> adj[];

Source(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 isCyclic(int v, boolean visited[], int parent) {
// Write code here
visited[v] = true;
Integer i;

Iterator<Integer> it = adj[v].iterator();
while (it.hasNext())

{
i = it.next();

if (!visited[i])
{
if (isCyclic(i, visited, v))
return true;

else if (i != parent)
return true;

}
return false;

public boolean isTree() {


// Write Code here
boolean visited[] = new boolean[vertexCount];
for (int i = 0; i < vertexCount; i++)

visited[i] = false;

if (isCyclic(0, visited, -1))


return false;

for (int u = 0; u < vertexCount; u++)


if (!visited[u])
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();

Source graph = new Source(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");
}
}
}
Question :3
Find kth largest element in a
stream
import java.util.*;

public class Source {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();
k = sc.nextInt();
int stream[] = new int[n];

for (int i = 0; i < n; i++) {

stream[i] = sc.nextInt();

// Write code here


}

private static int k;


private PriorityQueue<Integer> heap;

public Source(int k, int[] nums) {


this.k = k;
heap = new PriorityQueue<>();

for (int num: nums) {


heap.offer(num);
}

while (heap.size() > k) {


heap.poll();

}
}

public int add(int val) {


heap.offer(val);
if (heap.size() > k) {
heap.poll();
}

return heap.peek();
}

Question : 4
Sort Nearly Sorted Array
import java.util.*;

public class Source {

private static void sortArray(int[] arr,int n, int k) {


// Write code here

PriorityQueue<Integer> priorityQueue

= new PriorityQueue<>();

for (int i = 0; i < k + 1; i++) {

priorityQueue.add(arr[i]);

int index = 0;

for (int i = k + 1; i < n; i++) {

arr[index++] = priorityQueue.peek();
priorityQueue.poll();

priorityQueue.add(arr[i]);

Iterator<Integer> itr = priorityQueue.iterator();

while (itr.hasNext()) {

arr[index++] = priorityQueue.peek();

priorityQueue.poll();

}
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

int k = sc.nextInt();

int arr[] = new int[n];

for(int i = 0; i < n; i++){

arr[i] = sc.nextInt();

sortArray(arr,n, k);
for (int i = 0; i < arr.length; i++) {

System.out.print(arr[i] + " ");

}
Question : 5
Find Sum Between pth and
qth Smallest Elements
import java.util.*;

public class Source {


public static int sumBetweenPthToQthSmallestElement(int[] arr, int p, int q) {

// Write code here

Arrays.sort(arr);

int result=0;

for(int i=p;i<q-1;i++)

result+= arr[i];

return result;

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));

Question : 6
Find All Symmetric Pairs in
an Array
import java.util.*;
import java.util.HashMap;

public class Source {

public static void symmetricPair(int[][] arr) {


// Write code here

HashMap<Integer,Integer>hashing=new HashMap<Integer,Integer>();
for(int i=0;i<arr.length;i++){
int first = arr[i][0];
int second=arr[i][1];
Integer value=hashing.get(second);
if(value!=null && value==first)
System.out.println(second+" "+first);
else

hashing.put(first, second);
}

public static void main(String arg[]) {


Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int arr[][] = new int[row][2];
for(int i = 0 ; i < row ; i++){
for(int j = 0 ; j < 2 ; j++){
arr[i][j] = sc.nextInt();
}

}
symmetricPair(arr);
}
}

Question : 7
Find All Common Element in
All Rows of Matrix
import java.util.*;

public class Source {

public static void printElementInAllRows(int mat[][]) {

// Write code here


if (mat == null || mat.length == 0) {

return;

int row = mat.length;

int col = mat[0].length;

Map<Integer,Integer> mp = new HashMap<>();

for (int j = 0; j <col; j++)

mp.put(mat[0][j],1);

for (int i = 1; i < row; i++)

for (int j = 0; j < col; j++)

{
if (mp.get(mat[i][j]) != null && mp.get(mat[i][j]) == i)

mp.put(mat[i][j], i + 1);

if (i == row - 1)

System.out.print(mat[i][j] + " ");

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);
}

Question : 8
Find Itinerary in Order
import java.util.*;

public class Source {

public static void findItinerary(Map<String, String> tickets) {

// Write code here

Map<String, String> reverseMap = new HashMap<String, String>();


for (Map.Entry<String,String> entry: tickets.entrySet())

reverseMap.put(entry.getValue(), entry.getKey());

String start = null;

for (Map.Entry<String,String> entry: tickets.entrySet())

if (!reverseMap.containsKey(entry.getKey()))

start = entry.getKey();

break;

}
}

if (start == null)

System.out.println("Invalid Input");

return;

String to = tickets.get(start);

while (to != null)

System.out.println(start + "->" + to );
start = to;

to = tickets.get(to);

public static void main(String[] args) {

Map<String, String> tickets = new HashMap<String, String>();

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);

question :9
import java.util.*;

public class Source {

public static int search(int arr[], int left, int right, int key) {

// Write code here

if (left > right)

return -1;
int mid = (left + right) / 2;

if (arr[mid] == key)

return mid;

if (arr[left] <= arr[mid]) {

if (key >= arr[left] && key <= arr[mid])

return search(arr, left, mid - 1, key);

return search(arr, mid + 1, right, key);


}

if (key >= arr[mid] && key <= arr[right])

return search(arr, mid + 1, right, key);

return search(arr, left, mid - 1, key);

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 i = search(arr, 0, n - 1, key);

if (i != -1) {

System.out.println(i);

} else {

System.out.println("-1");

}
}

Question : 10
Find Median After
Merging Two Sorted
Arrays
import java.util.*;

public class Source {

public static int median(int[] arr1, int[] arr2 , int n){

// Write code here


int i = 0;

int j = 0;

int count;

int median1 = -1, median2 = -1;

for (count = 0; count <= n; count++)

if (i == n)

median1 = median2;

median2 = arr2[0];
break;

else if (j == n)

median1 = median2;

median2 = arr1[0];

break;

if (arr1[i] <= arr2[j])

{
median1 = median2;

median2 = arr1[i];

i++;

else

median1 = median2;

median2 = arr2[j];

j++;

}
}

return (median1 + median2)/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));

NOTE : EVERY CODES ARE CORRECT AND ACCEPTED IT MAY IN CLUDE


NAME : Amarnath Kumar Sharma
DSA ASSIGNMENT

You might also like