0% found this document useful (0 votes)
198 views

ALL QUESTIONS FOR JUSPAY

The document contains multiple Java code snippets addressing various algorithmic problems, including finding the maximum weight node in a graph, determining the nearest meeting cell, operations on a locking tree, finding the largest sum cycle, counting stars between bars, and solving the vampire battle problem. Each section provides a brief description of the problem, input format, and sample code implementation. The document also includes problems related to duplicates in email lists, setting matrix zeros, and the stock span problem.

Uploaded by

ilakkiyanj01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
198 views

ALL QUESTIONS FOR JUSPAY

The document contains multiple Java code snippets addressing various algorithmic problems, including finding the maximum weight node in a graph, determining the nearest meeting cell, operations on a locking tree, finding the largest sum cycle, counting stars between bars, and solving the vampire battle problem. Each section provides a brief description of the problem, input format, and sample code implementation. The document also includes problems related to duplicates in email lists, setting matrix zeros, and the stock span problem.

Uploaded by

ilakkiyanj01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

MAXIMUM WEIGHT NODE

// Java code for the above approach:


import java.util.*;
class GFG {
// Function to find Max Weight Cell
public static int maxWeightCell(int N, List<Integer> Edge)
{
// Initializing temp with 0
int[] temp = new int[N];

// Traversing the Edge array


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

// Checking if the value is not


// equal to -1
if (Edge.get(i) != -1) {
// Adding weight to the
// destination cell
temp[Edge.get(i)] += i;
}
}
// Getting the index with
// maximum value
int ans = 0;
int max = Integer.MIN_VALUE;
for (int i = 0; i < N; i++) {
if (temp[i] > max) {
ans = i;
max = temp[i];
}
}
return ans;
}
// Drivers code
public static void main(String[] args)
{
// Size of Edge
int N = 4;
List<Integer> Edge = Arrays.asList(2, 0, -1, 2);

// Printing value
System.out.println(maxWeightCell(N, Edge));
}
}

// This Code is Contributed by Prasad Kandekar(prasad264)


NEAREST MEETING CELL

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class NearestMeeting {


public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("./input.txt");
Scanner scanner = new Scanner(inputFile);

// Input the number of cells


int N = scanner.nextInt();
int[] edge = new int[N];

// Input the edges


for (int i = 0; i < N; i++) {
edge[i] = scanner.nextInt();
}

// Input the two cells


int C1 = scanner.nextInt();
int C2 = scanner.nextInt();

// Call the method to find the nearest meeting cell


int result = findNearestMeetingCell(N, edge, C1, C2);
System.out.println(result);

scanner.close();
}

public static int findNearestMeetingCell(int N, int[] edge, int C1, int C2) {
// Get distances from both cells using BFS
int[] distFromC1 = bfs(N, edge, C1);
int[] distFromC2 = bfs(N, edge, C2);

// Find the nearest meeting cell


int minDistance = Integer.MAX_VALUE;
int meetingCell = -1;

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


// Cell must be reachable from both C1 and C2
if (distFromC1[i] != -1 && distFromC2[i] != -1) {
int maxDist = Math.max(distFromC1[i], distFromC2[i]);
if (maxDist < minDistance) {
minDistance = maxDist;
meetingCell = i;
}
}
}

return meetingCell;
}

private static int[] bfs(int N, int[] edge, int start) {


int[] dist = new int[N];
Arrays.fill(dist, -1); // Initialize distances to -1 (unreachable)
Queue<Integer> queue = new LinkedList<>();

// Start BFS from the given cell


queue.add(start);
dist[start] = 0;

while (!queue.isEmpty()) {
int current = queue.poll();
int next = edge[current];

// If next cell is valid and not visited


if (next != -1 && dist[next] == -1) {
dist[next] = dist[current] + 1;
queue.add(next);
}
}

return dist;
}
}

OPERATION ON TREE
class LockingTree {
int[] parent;
int[] locked;
ArrayList<Integer>[] child;
public LockingTree(int[] parent) {
this.parent=parent;
this.locked=new int[parent.length];
this.child = new ArrayList[parent.length];

for(int i=0;i<child.length;i++){
child[i] = new ArrayList<>();
}

for(int i=1;i<parent.length;i++){
child[parent[i]].add(i);
}
}

public boolean lock(int num, int user) {


if(locked[num]==0){
locked[num]=user;
return true;
}
return false;
}

public boolean unlock(int num, int user) {


if(locked[num]==user){
locked[num]=0;
return true;
}
return false;
}

public boolean upgrade(int num, int user) {


if(locked[num]!=0){
return false;
}
int ancestor = parent[num];
while(ancestor!=-1){
if(locked[ancestor]!=0){
return false;
}
ancestor = parent[ancestor];
}
if(!hasLockedDescendant(num)){
return false;
}
else{
unlockAll(num);
locked[num]=user;
return true;
}
}

private boolean hasLockedDescendant(int num){


if(locked[num]!=0){
return true;
}
for(int x:child[num]){
if(hasLockedDescendant(x)){
return true;
}
}
return false;
}

private void unlockAll(int num){


locked[num]=0;
for(int x:child[num]){
unlockAll(x);
}
}
}
LARGEST SUM CYCLE
// Java code for the approach

import java.util.*;

public class GFG {


// adjacency list
static List<List<Integer> > adj = new ArrayList<>();
// arrays for tracking visited nodes and their parent
// nodes
static int[] vis, par;
// temporary list for storing nodes in a cycle
static List<Integer> tmp = new ArrayList<>();

// DFS function to find cycles and their sum


static long dfs(int node, int p)
{
vis[node] = 1;
par[node] = p;
tmp.add(node);
for (int i : adj.get(node)) {
if (vis[i] == 0) {
long z = dfs(i, node);
if (z != -1) {
return z;
}
}
else if (vis[i] == 1) {
long sum = i;
while (node != i) {
sum += node;
node = par[node];
}
if (node == i) {
return sum;
}
return -1;
}
}
return -1;
}

// Function to find largest sum cycle


static long largestSumCycle(int N, List<Integer> Edge)
{
long ans = -1;
vis = new int[N];
adj = new ArrayList<>(N);
par = new int[N];

// creating adjacency list


for (int i = 0; i < N; i++) {
adj.add(new ArrayList<>());
if (Edge.get(i) != -1) {
adj.get(i).add(Edge.get(i));
}
}

// finding cycles and their sum using DFS


for (int i = 0; i < N; i++) {
if (vis[i] == 0) {
ans = Math.max(ans, dfs(i, -1));
for (int j : tmp) {
vis[j] = 2;
}
tmp.clear();
}
}

return ans;
}

// Driver Code
public static void main(String[] args)
{
int N = 4;
List<Integer> Edge = Arrays.asList(1, 2, 0, -1);

// Function Call
long ans = largestSumCycle(N, Edge);
System.out.println(ans);
}
}

Stars Between Bars


Given a string s consisting of stars “*” and bars “|” ,an array of starting indices starIndex, and an array of ending
indices endIndex, determine the number of stars between any two bars within the substrings between the two
indices inclusive . NOTE that in this problem indexing starts at 0.

 A Star is represented as an asterisk [*=ascii decimal 42]

 A Bar is represented as a Pipe [“|”=ascii decimal 124]

Example

s=’|**|*|’
n=2
startIndex=[0,0]
endIndex=[4,5]

 For the first pair of indices (0,4) the substrings is “|**|*” . There are 2 stars between a pair of bars

 For the second pair of indices (0,5) the substring is “|**|*|” and there are 2+1=3 stars in between the
bars.
 Both of the answers are returned to the array [2,3].

Constraints

 1 <= n <= 105

 1 <= StartIndex[i] <= endIndex[i]

 Each Character of s is either “*” or “|”

Input Format for Custom testing

First line contains a string S. The next line contains an integer n , the no.of elements in startIndex and endIndex.
Each line i of the n subsequent lines contains an integer of startIndex. Each line i of the n subsequent lines contains
an integer of endindex.

Sample Input

*|*| → s=”*|*|”
1 → size of startindex[] and endIndex[] is 1.
0 → startindex = 0
2 → endindex = 2

Sample output:

Explanation :

The substring from index = 0 to index = 2 is “*|*” . there is no consecutive pair of bars in this string.

import java.util.*;

class Main
{
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String str = scn.next();
int n = scn.nextInt();
int startIndex[] = new int[n];
int endIndex[] = new int[n];
for(int i = 0; i < n; i++)
{
startIndex[i] = scn.nextInt();
}
for(int i = 0; i < n; i++)
{
endIndex[i] = scn.nextInt();
}
int len = str.length();
int counter[] = new int[len];
int count = 0;
int lastIdx = -1;

Arrays.fill(counter, -1);
Stack<Integer> st = new Stack<>();
for(int i = 0; i < len; i++)
{
char ch = str.charAt(i);
if(ch == '|')
{
while(!st.empty())
{
int idx = st.pop();
counter[idx] = i;
}
}
st.push(i);
}

int ansArr[] = new int[n];


for(int i = 0; i < n; i++)
{
int sIndex = startIndex[i];
int eIndex = endIndex[i];
int sCount = 0;
if(str.charAt(sIndex) != '|')
sIndex = counter[sIndex];
if(sIndex == -1 || counter[sIndex] == -1)
{
ansArr[i] = 0;
continue;
}
while(sIndex < eIndex)
{
int nextIdx = counter[sIndex];
if((nextIdx != -1) && (nextIdx <= eIndex))
{
sCount += nextIdx - sIndex - 1;
}
sIndex = nextIdx;
}
ansArr[i] = sCount;
}

for(int ele : ansArr)


{
System.out.print(ele + " ");
}
}
}
Vampire Battle
Stephan is a vampire. And he is fighting with his brother Damon. Vampires get energy from human bloods, so they
need to feed on human blood, killing the human beings. Stephan is also less inhuman, so he will like to take less
life in his hand. Now all the people’s blood has some power, which increases the powers of the Vampire. Stephan
just needs to be more powerful than Damon, killing the least human possible. Tell the total power Stephan will
have after drinking the bloods before the battle.

Note : Damon is a beast, so no human being will be left after Damon drinks everyone’s blood. But Stephan always
comes early in the town.

Input Format:

 First line with the number of people in the town, n.

 Second line with a string with n characters, denoting the one digit power in every blood.

Output Format:

Total minimum power Stephan will gather before the battle.

Constraints:

 1 <= n <= 10^4

Sample input:

 6

 093212

Sample output

 9

Explanation:

Stephan riches the town, drinks the blood with power 9. Now Damon cannot reach 9 by drinking all the other
bloods.

import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String str=sc.next();
char arr[]=str.toCharArray();
int a[]=new int[arr.length];
for(int i=0;i<a.length;i++)
a[i]=Integer.parseInt(arr[i]+"");

Arrays.sort(a);
int sum=0;
for(int i=0;i<a.length;i++) sum=sum+a[i]; int sumA=0; int sumB=sum;
ArrayList subsetA=new ArrayList(); for(int i=a.length-1;i>=0;i--)
{
sumA=sumA+a[i];
sumB=sumB-a[i];
subsetA.add(a[i]);
if(sumA>sumB)
break;
}

Iterator itr=subsetA.iterator();
while(itr.hasNext())
{

System.out.print((Integer)itr.next());
}
}
}
Duplicates
The principal has a problem with repetitions. Everytime someone sends the same email twice he becomes angry
and starts yelling. His personal assistant filters the mails so that all the unique mails are sent only once, and if
there is someone sending the same mail again and again, he deletes them. Write a program which will see the list
of roll numbers of the student and find how many emails are to be deleted.

Input Format:

 First line takes n, which is the total no. of mails recieved.

 Second line takes the n no. of email id as input./li>

Output Format:

Total no. of duplicate email id’s to be deleted.

Constraints:

 1 <= n <= 10^4

Sample input:

 6

 133433

Sample output

 3

import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
TreeSet list=new TreeSet<>();
for(int i=0;i<n;i++)
list.add(sc.nextInt());

System.out.println(Math.abs(n-list.size()));
}
}
SET MATRIX ZERO :
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.

You must do it in place.

class Solution {
public void setZeroes(int[][] matrix) {
boolean[][] flag = new boolean[matrix.length][matrix[0].length];
for(int i=0;i<matrix.length;i++)
{
for(int j=0;j<matrix[0].length;j++)
{
if(matrix[i][j] == 0 && flag[i][j] == false)
{
flag[i][j] = true;
for(int a=0;a<matrix[0].length;a++)
{
if(matrix[i][a] != 0)
{
flag[i][a] = true;
matrix[i][a] = 0;
}
}
for(int a=0;a<matrix.length;a++)
{
if(matrix[a][j] != 0)
{
flag[a][j] = true;
matrix[a][j] = 0;
}
}
}
}
}

}
}

STOCK SPAN PROBLEM :


Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for
the current day.

The span of the stock's price in one day is the maximum number of consecutive days (starting from that day and
going backward) for which the stock price was less than or equal to the price of that day.

 For example, if the prices of the stock in the last four days is [7,2,1,2] and the price of the stock today is 2,
then the span of today is 4 because starting from today, the price of the stock was less than or
equal 2 for 4 consecutive days.

 Also, if the prices of the stock in the last four days is [7,34,1,2] and the price of the stock today is 8, then
the span of today is 3 because starting from today, the price of the stock was less than or
equal 8 for 3 consecutive days.

Implement the StockSpanner class:


 StockSpanner() Initializes the object of the class.

 int next(int price) Returns the span of the stock's price given that today's price is price.

class StockSpanner {
Stack<Pair> stack;

public StockSpanner() {
this.stack = new Stack<>();
}

public int next(int price) {


Pair newpair = new Pair(price, 1);
while(!stack.empty() && stack.peek().price <= newpair.price)
{
newpair.count += stack.peek().count;
stack.pop();
}
stack.push(newpair);
return newpair.count;
}
}

class Pair{
int price;
int count;
public Pair(int n, int c)
{
this.price = n;
this.count = c;
}
}

/**
* Your StockSpanner object will be instantiated and called as such:
* StockSpanner obj = new StockSpanner();
* int param_1 = obj.next(price);
*/

LARGEST CYCLE LENGTH :


class Solution {
private int maxCycle;

public int longestCycle(int[] edges) {


int n = edges.length;
maxCycle = -1;
int[] visited = new int[n];
boolean[] inPath = new boolean[n];

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


if (visited[i] == 0) {
dfs(edges, i, 1, visited, inPath);
}
}
return maxCycle;
}

private void dfs(int[] edges, int curr, int time, int[] visited, boolean[] inPath)
{
if (curr == -1) {
return;
}

if (inPath[curr]) {
maxCycle = Math.max(maxCycle, time - visited[curr]);
return;
}

if (visited[curr] > 0) {
return;
}

visited[curr] = time;
inPath[curr] = true;

dfs(edges, edges[curr], time + 1, visited, inPath);


inPath[curr] = false;
}
}

You might also like