content
stringlengths 219
31.2k
| complexity
stringclasses 5
values | file_name
stringlengths 6
9
| complexity_ranked
float64 0.1
0.9
|
|---|---|---|---|
// Java program to check if all leaf nodes are at
// same level of binary tree
import
java.util.*;
// User defined node class
class
Node {
int
data;
Node left, right;
// Constructor to create a new tree node
Node(
int
key) {
int
data = key;
left = right =
null
;
}
}
class
GFG {
// return true if all leaf nodes are
// at same level, else false
static
boolean
checkLevelLeafNode(Node root)
{
if
(root ==
null
)
return
true
;
// create a queue for level order traversal
Queue<Node> q =
new
LinkedList<>();
q.add(root);
int
result = Integer.MAX_VALUE;
int
level =
0
;
// traverse until the queue is empty
while
(q.size() !=
0
) {
int
size = q.size();
level++;
// traverse for complete level
while
(size >
0
) {
Node temp = q.remove();
// check for left child
if
(temp.left !=
null
) {
q.add(temp.left);
// if its leaf node
if
(temp.left.left ==
null
&& temp.left.right ==
null
) {
// if it's first leaf node, then update result
if
(result == Integer.MAX_VALUE)
result = level;
// if it's not first leaf node, then compare
// the level with level of previous leaf node.
else
if
(result != level)
return
false
;
}
}
// check for right child
if
(temp.right !=
null
) {
q.add(temp.right);
// if its leaf node
if
(temp.right.left ==
null
&& temp.right.right ==
null
) {
// if it's first leaf node, then update result
if
(result == Integer.MAX_VALUE)
result = level;
// if it's not first leaf node, then compare
// the level with level of previous leaf node.
else
if
(result != level)
return
false
;
}
}
size--;
}
}
return
true
;
}
// Driver code
public
static
void
main(String args[])
{
// construct a tree
Node root =
new
Node(
1
);
root.left =
new
Node(
2
);
root.right =
new
Node(
3
);
root.left.right =
new
Node(
4
);
root.right.left =
new
Node(
5
);
root.right.right =
new
Node(
6
);
boolean
result = checkLevelLeafNode(root);
if
(result ==
true
)
System.out.println(
"All leaf nodes are at same level"
);
else
System.out.println(
"Leaf nodes not at same level"
);
}
}
// This code is contributed by rachana soma
|
n
|
420.java
| 0.5
|
// Java program to check if there exist an edge whose
// removal creates two trees of same size
class
Node
{
int
key;
Node left, right;
public
Node(
int
key)
{
this
.key = key;
left = right =
null
;
}
}
class
Res
{
boolean
res =
false
;
}
class
BinaryTree
{
Node root;
// To calculate size of tree with given root
int
count(Node node)
{
if
(node ==
null
)
return
0
;
return
count(node.left) + count(node.right) +
1
;
}
// This function returns size of tree rooted with given
// root. It also set "res" as true if there is an edge
// whose removal divides tree in two halves.
// n is size of tree
int
checkRec(Node root,
int
n, Res res)
{
// Base case
if
(root ==
null
)
return
0
;
// Compute sizes of left and right children
int
c = checkRec(root.left, n, res) +
1
+ checkRec(root.right, n, res);
// If required property is true for current node
// set "res" as true
if
(c == n - c)
res.res =
true
;
// Return size
return
c;
}
// This function mainly uses checkRec()
boolean
check(Node root)
{
// Count total nodes in given tree
int
n = count(root);
// Initialize result and recursively check all nodes
Res res =
new
Res();
checkRec(root, n, res);
return
res.res;
}
// Driver code
public
static
void
main(String[] args)
{
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(
5
);
tree.root.left =
new
Node(
1
);
tree.root.right =
new
Node(
6
);
tree.root.left.left =
new
Node(
3
);
tree.root.right.left =
new
Node(
7
);
tree.root.right.right =
new
Node(
4
);
if
(tree.check(tree.root) ==
true
)
System.out.println(
"YES"
);
else
System.out.println(
"NO"
);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
|
n
|
422.java
| 0.5
|
// Java program to check whether a given
// Binary Tree is Perfect or not
class
GfG {
/* Tree node structure */
static
class
Node
{
int
key;
Node left, right;
}
// Returns depth of leftmost leaf.
static
int
findADepth(Node node)
{
int
d =
0
;
while
(node !=
null
)
{
d++;
node = node.left;
}
return
d;
}
/* This function tests if a binary tree is perfect
or not. It basically checks for two things :
1) All leaves are at same level
2) All internal nodes have two children */
static
boolean
isPerfectRec(Node root,
int
d,
int
level)
{
// An empty tree is perfect
if
(root ==
null
)
return
true
;
// If leaf node, then its depth must be same as
// depth of all other leaves.
if
(root.left ==
null
&& root.right ==
null
)
return
(d == level+
1
);
// If internal node and one child is empty
if
(root.left ==
null
|| root.right ==
null
)
return
false
;
// Left and right subtrees must be perfect.
return
isPerfectRec(root.left, d, level+
1
) && isPerfectRec(root.right, d, level+
1
);
}
// Wrapper over isPerfectRec()
static
boolean
isPerfect(Node root)
{
int
d = findADepth(root);
return
isPerfectRec(root, d,
0
);
}
/* Helper function that allocates a new node with the
given key and NULL left and right pointer. */
static
Node newNode(
int
k)
{
Node node =
new
Node();
node.key = k;
node.right =
null
;
node.left =
null
;
return
node;
}
// Driver Program
public
static
void
main(String args[])
{
Node root =
null
;
root = newNode(
10
);
root.left = newNode(
20
);
root.right = newNode(
30
);
root.left.left = newNode(
40
);
root.left.right = newNode(
50
);
root.right.left = newNode(
60
);
root.right.right = newNode(
70
);
if
(isPerfect(root) ==
true
)
System.out.println(
"Yes"
);
else
System.out.println(
"No"
);
}
}
|
n
|
424.java
| 0.5
|
// Java program to check if binay tree is full or not
/* Tree node structure */
class
Node
{
int
data;
Node left, right;
Node(
int
item)
{
data = item;
left = right =
null
;
}
}
class
BinaryTree
{
Node root;
/* this function checks if a binary tree is full or not */
boolean
isFullTree(Node node)
{
// if empty tree
if
(node ==
null
)
return
true
;
// if leaf node
if
(node.left ==
null
&& node.right ==
null
)
return
true
;
// if both left and right subtrees are not null
// the are full
if
((node.left!=
null
) && (node.right!=
null
))
return
(isFullTree(node.left) && isFullTree(node.right));
// if none work
return
false
;
}
// Driver program
public
static
void
main(String args[])
{
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(
10
);
tree.root.left =
new
Node(
20
);
tree.root.right =
new
Node(
30
);
tree.root.left.right =
new
Node(
40
);
tree.root.left.left =
new
Node(
50
);
tree.root.right.left =
new
Node(
60
);
tree.root.left.left.left =
new
Node(
80
);
tree.root.right.right =
new
Node(
70
);
tree.root.left.left.right =
new
Node(
90
);
tree.root.left.right.left =
new
Node(
80
);
tree.root.left.right.right =
new
Node(
90
);
tree.root.right.left.left =
new
Node(
80
);
tree.root.right.left.right =
new
Node(
90
);
tree.root.right.right.left =
new
Node(
80
);
tree.root.right.right.right =
new
Node(
90
);
if
(tree.isFullTree(tree.root))
System.out.print(
"The binary tree is full"
);
else
System.out.print(
"The binary tree is not full"
);
}
}
// This code is contributed by Mayank Jaiswal
|
n
|
425.java
| 0.5
|
//A Java program to check if a given binary tree is complete or not
import
java.util.LinkedList;
import
java.util.Queue;
public
class
CompleteBTree
{
/* A binary tree node has data, a pointer to left child
and a pointer to right child */
static
class
Node
{
int
data;
Node left;
Node right;
// Constructor
Node(
int
d)
{
data = d;
left =
null
;
right =
null
;
}
}
/* Given a binary tree, return true if the tree is complete
else false */
static
boolean
isCompleteBT(Node root)
{
// Base Case: An empty tree is complete Binary Tree
if
(root ==
null
)
return
true
;
// Create an empty queue
Queue<Node> queue =
new
LinkedList<>();
// Create a flag variable which will be set true
// when a non full node is seen
boolean
flag =
false
;
// Do level order traversal using queue.
queue.add(root);
while
(!queue.isEmpty())
{
Node temp_node = queue.remove();
/* Check if left child is present*/
if
(temp_node.left !=
null
)
{
// If we have seen a non full node, and we see a node
// with non-empty left child, then the given tree is not
// a complete Binary Tree
if
(flag ==
true
)
return
false
;
// Enqueue Left Child
queue.add(temp_node.left);
}
// If this a non-full node, set the flag as true
else
flag =
true
;
/* Check if right child is present*/
if
(temp_node.right !=
null
)
{
// If we have seen a non full node, and we see a node
// with non-empty right child, then the given tree is not
// a complete Binary Tree
if
(flag ==
true
)
return
false
;
// Enqueue Right Child
queue.add(temp_node.right);
}
// If this a non-full node, set the flag as true
else
flag =
true
;
}
// If we reach here, then the tree is complete Binary Tree
return
true
;
}
/* Driver program to test above functions*/
public
static
void
main(String[] args)
{
/* Let us construct the following Binary Tree which
is not a complete Binary Tree
1
/ \
2 3
/ \ \
4 5 6
*/
Node root =
new
Node(
1
);
root.left =
new
Node(
2
);
root.right =
new
Node(
3
);
root.left.left =
new
Node(
4
);
root.left.right =
new
Node(
5
);
root.right.right =
new
Node(
6
);
if
(isCompleteBT(root) ==
true
)
System.out.println(
"Complete Binary Tree"
);
else
System.out.println(
"NOT Complete Binary Tree"
);
}
}
//This code is contributed by Sumit Ghosh
|
n
|
426.java
| 0.5
|
// Java program to check if binary tree
// is subtree of another binary tree
class
Node {
char
data;
Node left, right;
Node(
char
item)
{
data = item;
left = right =
null
;
}
}
class
Passing {
int
i;
int
m =
0
;
int
n =
0
;
}
class
BinaryTree {
static
Node root;
Passing p =
new
Passing();
String strstr(String haystack, String needle)
{
if
(haystack ==
null
|| needle ==
null
) {
return
null
;
}
int
hLength = haystack.length();
int
nLength = needle.length();
if
(hLength < nLength) {
return
null
;
}
if
(nLength ==
0
) {
return
haystack;
}
for
(
int
i =
0
; i <= hLength - nLength; i++) {
if
(haystack.charAt(i) == needle.charAt(
0
)) {
int
j =
0
;
for
(; j < nLength; j++) {
if
(haystack.charAt(i + j) != needle.charAt(j)) {
break
;
}
}
if
(j == nLength) {
return
haystack.substring(i);
}
}
}
return
null
;
}
// A utility function to store inorder traversal of tree rooted
// with root in an array arr[]. Note that i is passed as reference
void
storeInorder(Node node,
char
arr[], Passing i)
{
if
(node ==
null
) {
arr[i.i++] =
'$'
;
return
;
}
storeInorder(node.left, arr, i);
arr[i.i++] = node.data;
storeInorder(node.right, arr, i);
}
// A utility function to store preorder traversal of tree rooted
// with root in an array arr[]. Note that i is passed as reference
void
storePreOrder(Node node,
char
arr[], Passing i)
{
if
(node ==
null
) {
arr[i.i++] =
'$'
;
return
;
}
arr[i.i++] = node.data;
storePreOrder(node.left, arr, i);
storePreOrder(node.right, arr, i);
}
/* This function returns true if S is a subtree of T, otherwise false */
boolean
isSubtree(Node T, Node S)
{
/* base cases */
if
(S ==
null
) {
return
true
;
}
if
(T ==
null
) {
return
false
;
}
// Store Inorder traversals of T and S in inT[0..m-1]
// and inS[0..n-1] respectively
char
inT[] =
new
char
[
100
];
String op1 = String.valueOf(inT);
char
inS[] =
new
char
[
100
];
String op2 = String.valueOf(inS);
storeInorder(T, inT, p);
storeInorder(S, inS, p);
inT[p.m] =
'\0'
;
inS[p.m] =
'\0'
;
// If inS[] is not a substring of preS[], return false
if
(strstr(op1, op2) !=
null
) {
return
false
;
}
// Store Preorder traversals of T and S in inT[0..m-1]
// and inS[0..n-1] respectively
p.m =
0
;
p.n =
0
;
char
preT[] =
new
char
[
100
];
char
preS[] =
new
char
[
100
];
String op3 = String.valueOf(preT);
String op4 = String.valueOf(preS);
storePreOrder(T, preT, p);
storePreOrder(S, preS, p);
preT[p.m] =
'\0'
;
preS[p.n] =
'\0'
;
// If inS[] is not a substring of preS[], return false
// Else return true
return
(strstr(op3, op4) !=
null
);
}
// Driver program to test above functions
public
static
void
main(String args[])
{
BinaryTree tree =
new
BinaryTree();
Node T =
new
Node(
'a'
);
T.left =
new
Node(
'b'
);
T.right =
new
Node(
'd'
);
T.left.left =
new
Node(
'c'
);
T.right.right =
new
Node(
'e'
);
Node S =
new
Node(
'a'
);
S.left =
new
Node(
'b'
);
S.right =
new
Node(
'd'
);
S.left.left =
new
Node(
'c'
);
if
(tree.isSubtree(T, S)) {
System.out.println(
"Yes, S is a subtree of T"
);
}
else
{
System.out.println(
"No, S is not a subtree of T"
);
}
}
}
// This code is contributed by Mayank Jaiswal
|
n
|
428.java
| 0.5
|
// Java program to see if two trees
// are mirror of each other
// A binary tree node
class
Node
{
int
data;
Node left, right;
public
Node(
int
data)
{
this
.data = data;
left = right =
null
;
}
}
class
BinaryTree
{
Node a, b;
/* Given two trees, return true if they are
mirror of each other */
boolean
areMirror(Node a, Node b)
{
/* Base case : Both empty */
if
(a ==
null
&& b ==
null
)
return
true
;
// If only one is empty
if
(a ==
null
|| b ==
null
)
return
false
;
/* Both non-empty, compare them recursively
Note that in recursive calls, we pass left
of one tree and right of other tree */
return
a.data == b.data
&& areMirror(a.left, b.right)
&& areMirror(a.right, b.left);
}
// Driver code to test above methods
public
static
void
main(String[] args)
{
BinaryTree tree =
new
BinaryTree();
Node a =
new
Node(
1
);
Node b =
new
Node(
1
);
a.left =
new
Node(
2
);
a.right =
new
Node(
3
);
a.left.left =
new
Node(
4
);
a.left.right =
new
Node(
5
);
b.left =
new
Node(
3
);
b.right =
new
Node(
2
);
b.right.left =
new
Node(
5
);
b.right.right =
new
Node(
4
);
if
(tree.areMirror(a, b) ==
true
)
System.out.println(
"Yes"
);
else
System.out.println(
"No"
);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
|
n
|
429.java
| 0.5
|
// Java implementation of worst
// case linear time algorithm
// to find k'th smallest element
import
java.util.*;
class
GFG
{
// int partition(int arr[], int l, int r, int k);
// A simple function to find median of arr[]. This is called
// only for an array of size 5 in this program.
static
int
findMedian(
int
arr[],
int
i,
int
n)
{
if
(i <= n)
Arrays.sort(arr, i, n);
// Sort the array
else
Arrays.sort(arr, n, i);
return
arr[n/
2
];
// Return middle element
}
// Returns k'th smallest element
// in arr[l..r] in worst case
// linear time. ASSUMPTION: ALL
// ELEMENTS IN ARR[] ARE DISTINCT
static
int
kthSmallest(
int
arr[],
int
l,
int
r,
int
k)
{
// If k is smaller than
// number of elements in array
if
(k >
0
&& k <= r - l +
1
)
{
int
n = r - l +
1
;
// Number of elements in arr[l..r]
// Divide arr[] in groups of size 5,
// calculate median of every group
// and store it in median[] array.
int
i;
// There will be floor((n+4)/5) groups;
int
[]median =
new
int
[(n +
4
) /
5
];
for
(i =
0
; i < n/
5
; i++)
median[i] = findMedian(arr,l + i *
5
,
5
);
// For last group with less than 5 elements
if
(i*
5
< n)
{
median[i] = findMedian(arr,l + i *
5
, n %
5
);
i++;
}
// Find median of all medians using recursive call.
// If median[] has only one element, then no need
// of recursive call
int
medOfMed = (i ==
1
)? median[i -
1
]:
kthSmallest(median,
0
, i -
1
, i /
2
);
// Partition the array around a random element and
// get position of pivot element in sorted array
int
pos = partition(arr, l, r, medOfMed);
// If position is same as k
if
(pos-l == k -
1
)
return
arr[pos];
if
(pos-l > k -
1
)
// If position is more, recur for left
return
kthSmallest(arr, l, pos -
1
, k);
// Else recur for right subarray
return
kthSmallest(arr, pos +
1
, r, k - pos + l -
1
);
}
// If k is more than number of elements in array
return
Integer.MAX_VALUE;
}
static
int
[] swap(
int
[]arr,
int
i,
int
j)
{
int
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return
arr;
}
// It searches for x in arr[l..r], and
// partitions the array around x.
static
int
partition(
int
arr[],
int
l,
int
r,
int
x)
{
// Search for x in arr[l..r] and move it to end
int
i;
for
(i = l; i < r; i++)
if
(arr[i] == x)
break
;
swap(arr, i, r);
// Standard partition algorithm
i = l;
for
(
int
j = l; j <= r -
1
; j++)
{
if
(arr[j] <= x)
{
swap(arr, i, j);
i++;
}
}
swap(arr, i, r);
return
i;
}
// Driver code
public
static
void
main(String[] args)
{
int
arr[] = {
12
,
3
,
5
,
7
,
4
,
19
,
26
};
int
n = arr.length, k =
3
;
System.out.println(
"K'th smallest element is "
+ kthSmallest(arr,
0
, n -
1
, k));
}
}
// This code has been contributed by 29AjayKumar
|
n
|
43.java
| 0.5
|
// Java implementation to check whether the two
// binary tress are mirrors of each other or not
import
java.util.*;
class
GfG {
// structure of a node in binary tree
static
class
Node
{
int
data;
Node left, right;
}
// Utility function to create and return
// a new node for a binary tree
static
Node newNode(
int
data)
{
Node temp =
new
Node();
temp.data = data;
temp.left =
null
;
temp.right =
null
;
return
temp;
}
// function to check whether the two binary trees
// are mirrors of each other or not
static
String areMirrors(Node root1, Node root2)
{
Stack<Node> st1 =
new
Stack<Node> ();
Stack<Node> st2 =
new
Stack<Node> ();
while
(
true
)
{
// iterative inorder traversal of 1st tree and
// reverse inoder traversal of 2nd tree
while
(root1 !=
null
&& root2 !=
null
)
{
// if the corresponding nodes in the two traversal
// have different data values, then they are not
// mirrors of each other.
if
(root1.data != root2.data)
return
"No"
;
st1.push(root1);
st2.push(root2);
root1 = root1.left;
root2 = root2.right;
}
// if at any point one root becomes null and
// the other root is not null, then they are
// not mirrors. This condition verifies that
// structures of tree are mirrors of each other.
if
(!(root1 ==
null
&& root2 ==
null
))
return
"No"
;
if
(!st1.isEmpty() && !st2.isEmpty())
{
root1 = st1.peek();
root2 = st2.peek();
st1.pop();
st2.pop();
/* we have visited the node and its left subtree.
Now, it's right subtree's turn */
root1 = root1.right;
/* we have visited the node and its right subtree.
Now, it's left subtree's turn */
root2 = root2.left;
}
// both the trees have been completely traversed
else
break
;
}
// tress are mirrors of each other
return
"Yes"
;
}
// Driver program to test above
public
static
void
main(String[] args)
{
// 1st binary tree formation
Node root1 = newNode(
1
);
/* 1 */
root1.left = newNode(
3
);
/* / \ */
root1.right = newNode(
2
);
/* 3 2 */
root1.right.left = newNode(
5
);
/* / \ */
root1.right.right = newNode(
4
);
/* 5 4 */
// 2nd binary tree formation
Node root2 = newNode(
1
);
/* 1 */
root2.left = newNode(
2
);
/* / \ */
root2.right = newNode(
3
);
/* 2 3 */
root2.left.left = newNode(
4
);
/* / \ */
root2.left.right = newNode(
5
);
/* 4 5 */
System.out.println(areMirrors(root1, root2));
}
}
|
n
|
430.java
| 0.5
|
// Java program to see if two trees are identical
// A binary tree node
class
Node
{
int
data;
Node left, right;
Node(
int
item)
{
data = item;
left = right =
null
;
}
}
class
BinaryTree
{
Node root1, root2;
/* Given two trees, return true if they are
structurally identical */
boolean
identicalTrees(Node a, Node b)
{
/*1. both empty */
if
(a ==
null
&& b ==
null
)
return
true
;
/* 2. both non-empty -> compare them */
if
(a !=
null
&& b !=
null
)
return
(a.data == b.data
&& identicalTrees(a.left, b.left)
&& identicalTrees(a.right, b.right));
/* 3. one empty, one not -> false */
return
false
;
}
/* Driver program to test identicalTrees() function */
public
static
void
main(String[] args)
{
BinaryTree tree =
new
BinaryTree();
tree.root1 =
new
Node(
1
);
tree.root1.left =
new
Node(
2
);
tree.root1.right =
new
Node(
3
);
tree.root1.left.left =
new
Node(
4
);
tree.root1.left.right =
new
Node(
5
);
tree.root2 =
new
Node(
1
);
tree.root2.left =
new
Node(
2
);
tree.root2.right =
new
Node(
3
);
tree.root2.left.left =
new
Node(
4
);
tree.root2.left.right =
new
Node(
5
);
if
(tree.identicalTrees(tree.root1, tree.root2))
System.out.println(
"Both trees are identical"
);
else
System.out.println(
"Trees are not identical"
);
}
}
|
n
|
431.java
| 0.5
|
// Java program to see if there is a root to leaf path
// with given sequence.
public
class
CheckForPath {
// function to check given sequence of root to leaf path exist
// in tree or not.
// index represents current element in sequence of rooth to
// leaf path
public
static
boolean
existPath(Node root,
int
arr[],
int
index)
{
// If root is NULL, then there must not be any element
// in array.
if
(root==
null
)
{
return
arr.length==
0
;
}
// If this node is a leaf and matches with last entry
// of array.
if
((root.left==
null
&& root.right==
null
) && (root.data==arr[index]
&& root.data==arr[arr.length-
1
]))
{
return
true
;
}
// If current node is equal to arr[index] this means
// that till this level path has been matched and
// remaining path can be either in left subtree or
// right subtree.
return
(index<arr.length && (root.data==arr[index] &&
(existPath(root.left,arr,index+
1
) ||
existPath(root.right, arr, index+
1
))));
}
public
static
void
main(String args[]) {
// arr[] is sequence of root to leaf path
int
arr[] = {
5
,
8
,
6
,
7
};
Node root=
new
Node(
5
);
root.left=
new
Node(
3
);
root.right=
new
Node(
8
);
root.left.left =
new
Node(
2
);
root.left.right =
new
Node(
4
);
root.left.left.left =
new
Node(
1
);
root.right.left =
new
Node(
6
);
root.right.left.right =
new
Node(
7
);
if
(existPath(root, arr,
0
))
{
System.out.print(
"Path Exists"
);
}
else
{
System.out.print(
"Path does not Exist"
);
}
}
}
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class
Node
{
int
data;
Node left, right;
Node(
int
data)
{
this
.data=data;
left=right=
null
;
}
};
// This code is contributed by Gaurav Tiwari
|
n
|
432.java
| 0.5
|
// Java program to print cousins of a node
class
GfG {
// A Binary Tree Node
static
class
Node
{
int
data;
Node left, right;
}
// A utility function to create a new Binary
// Tree Node
static
Node newNode(
int
item)
{
Node temp =
new
Node();
temp.data = item;
temp.left =
null
;
temp.right =
null
;
return
temp;
}
/* It returns level of the node if it is present
in tree, otherwise returns 0.*/
static
int
getLevel(Node root, Node node,
int
level)
{
// base cases
if
(root ==
null
)
return
0
;
if
(root == node)
return
level;
// If node is present in left subtree
int
downlevel = getLevel(root.left, node, level+
1
);
if
(downlevel !=
0
)
return
downlevel;
// If node is not present in left subtree
return
getLevel(root.right, node, level+
1
);
}
/* Print nodes at a given level such that sibling of
node is not printed if it exists */
static
void
printGivenLevel(Node root, Node node,
int
level)
{
// Base cases
if
(root ==
null
|| level <
2
)
return
;
// If current node is parent of a node with
// given level
if
(level ==
2
)
{
if
(root.left == node || root.right == node)
return
;
if
(root.left !=
null
)
System.out.print(root.left.data +
" "
);
if
(root.right !=
null
)
System.out.print(root.right.data +
" "
);
}
// Recur for left and right subtrees
else
if
(level >
2
)
{
printGivenLevel(root.left, node, level-
1
);
printGivenLevel(root.right, node, level-
1
);
}
}
// This function prints cousins of a given node
static
void
printCousins(Node root, Node node)
{
// Get level of given node
int
level = getLevel(root, node,
1
);
// Print nodes of given level.
printGivenLevel(root, node, level);
}
// Driver Program to test above functions
public
static
void
main(String[] args)
{
Node root = newNode(
1
);
root.left = newNode(
2
);
root.right = newNode(
3
);
root.left.left = newNode(
4
);
root.left.right = newNode(
5
);
root.left.right.right = newNode(
15
);
root.right.left = newNode(
6
);
root.right.right = newNode(
7
);
root.right.left.right = newNode(
8
);
printCousins(root, root.left.right);
}
}
|
n
|
433.java
| 0.5
|
// Java implementation to print the path from root
// to a given node in a binary tree
import
java.util.ArrayList;
public
class
PrintPath {
// Returns true if there is a path from root
// to the given node. It also populates
// 'arr' with the given path
public
static
boolean
hasPath(Node root, ArrayList<Integer> arr,
int
x)
{
// if root is NULL
// there is no path
if
(root==
null
)
return
false
;
// push the node's value in 'arr'
arr.add(root.data);
// if it is the required node
// return true
if
(root.data == x)
return
true
;
// else check whether the required node lies
// in the left subtree or right subtree of
// the current node
if
(hasPath(root.left, arr, x) ||
hasPath(root.right, arr, x))
return
true
;
// required node does not lie either in the
// left or right subtree of the current node
// Thus, remove current node's value from
// 'arr'and then return false
arr.remove(arr.size()-
1
);
return
false
;
}
// function to print the path from root to the
// given node if the node lies in the binary tree
public
static
void
printPath(Node root,
int
x)
{
// ArrayList to store the path
ArrayList<Integer> arr=
new
ArrayList<>();
// if required node 'x' is present
// then print the path
if
(hasPath(root, arr, x))
{
for
(
int
i=
0
; i<arr.size()-
1
; i++)
System.out.print(arr.get(i)+
"->"
);
System.out.print(arr.get(arr.size() -
1
));
}
// 'x' is not present in the binary tree
else
System.out.print(
"No Path"
);
}
public
static
void
main(String args[]) {
Node root=
new
Node(
1
);
root.left =
new
Node(
2
);
root.right =
new
Node(
3
);
root.left.left =
new
Node(
4
);
root.left.right =
new
Node(
5
);
root.right.left =
new
Node(
6
);
root.right.right =
new
Node(
7
);
int
x=
5
;
printPath(root, x);
}
}
// A node of binary tree
class
Node
{
int
data;
Node left, right;
Node(
int
data)
{
this
.data=data;
left=right=
null
;
}
};
//This code is contributed by Gaurav Tiwari
|
n
|
434.java
| 0.5
|
// Recursive Java program to print odd level nodes
class
GfG {
static
class
Node {
int
data;
Node left, right;
}
static
void
printOddNodes(Node root,
boolean
isOdd)
{
// If empty tree
if
(root ==
null
)
return
;
// If current node is of odd level
if
(isOdd ==
true
)
System.out.print(root.data +
" "
);
// Recur for children with isOdd
// switched.
printOddNodes(root.left, !isOdd);
printOddNodes(root.right, !isOdd);
}
// Utility method to create a node
static
Node newNode(
int
data)
{
Node node =
new
Node();
node.data = data;
node.left =
null
;
node.right =
null
;
return
(node);
}
// Driver code
public
static
void
main(String[] args)
{
Node root = newNode(
1
);
root.left = newNode(
2
);
root.right = newNode(
3
);
root.left.left = newNode(
4
);
root.left.right = newNode(
5
);
printOddNodes(root,
true
);
}
}
|
n
|
435.java
| 0.5
|
// Iterative Java program to print odd level nodes
import
java.util.*;
class
GfG {
static
class
Node {
int
data;
Node left, right;
}
// Iterative method to do level order traversal line by line
static
void
printOddNodes(Node root)
{
// Base Case
if
(root ==
null
)
return
;
// Create an empty queue for level
// order tarversal
Queue<Node> q =
new
LinkedList<Node> ();
// Enqueue root and initialize level as odd
q.add(root);
boolean
isOdd =
true
;
while
(
true
)
{
// nodeCount (queue size) indicates
// number of nodes at current level.
int
nodeCount = q.size();
if
(nodeCount ==
0
)
break
;
// Dequeue all nodes of current level
// and Enqueue all nodes of next level
while
(nodeCount >
0
)
{
Node node = q.peek();
if
(isOdd ==
true
)
System.out.print(node.data +
" "
);
q.remove();
if
(node.left !=
null
)
q.add(node.left);
if
(node.right !=
null
)
q.add(node.right);
nodeCount--;
}
isOdd = !isOdd;
}
}
// Utility method to create a node
static
Node newNode(
int
data)
{
Node node =
new
Node();
node.data = data;
node.left =
null
;
node.right =
null
;
return
(node);
}
// Driver code
public
static
void
main(String[] args)
{
Node root = newNode(
1
);
root.left = newNode(
2
);
root.right = newNode(
3
);
root.left.left = newNode(
4
);
root.left.right = newNode(
5
);
printOddNodes(root);
}
}
|
n
|
436.java
| 0.5
|
// Java program to find the all full nodes in
// a given binary tree
public
class
FullNodes {
// Traverses given tree in Inorder fashion and
// prints all nodes that have both children as
// non-empty.
public
static
void
findFullNode(Node root)
{
if
(root !=
null
)
{
findFullNode(root.left);
if
(root.left !=
null
&& root.right !=
null
)
System.out.print(root.data+
" "
);
findFullNode(root.right);
}
}
public
static
void
main(String args[]) {
Node root =
new
Node(
1
);
root.left =
new
Node(
2
);
root.right =
new
Node(
3
);
root.left.left =
new
Node(
4
);
root.right.left =
new
Node(
5
);
root.right.right =
new
Node(
6
);
root.right.left.right =
new
Node(
7
);
root.right.right.right =
new
Node(
8
);
root.right.left.right.left =
new
Node(
9
);
findFullNode(root);
}
}
/* A binary tree node */
class
Node
{
int
data;
Node left, right;
Node(
int
data)
{
left=right=
null
;
this
.data=data;
}
};
//This code is contributed by Gaurav Tiwari
|
n
|
437.java
| 0.5
|
// Java implementation to find
// the sum of all the parent
// nodes having child node x
class
GFG
{
// sum
static
int
sum =
0
;
// Node of a binary tree
static
class
Node
{
int
data;
Node left, right;
};
// function to get a new node
static
Node getNode(
int
data)
{
// allocate memory for the node
Node newNode =
new
Node();
// put in the data
newNode.data = data;
newNode.left = newNode.right =
null
;
return
newNode;
}
// function to find the sum of all the
// parent nodes having child node x
static
void
sumOfParentOfX(Node root,
int
x)
{
// if root == NULL
if
(root ==
null
)
return
;
// if left or right child
// of root is 'x', then
// add the root's data to 'sum'
if
((root.left !=
null
&& root.left.data == x) ||
(root.right !=
null
&& root.right.data == x))
sum += root.data;
// recursively find the required
// parent nodes in the left and
// right subtree
sumOfParentOfX(root.left, x);
sumOfParentOfX(root.right, x);
}
// utility function to find the
// sum of all the parent nodes
// having child node x
static
int
sumOfParentOfXUtil(Node root,
int
x)
{
sum =
0
;
sumOfParentOfX(root, x);
// required sum of parent nodes
return
sum;
}
// Driver Code
public
static
void
main(String args[])
{
// binary tree formation
Node root = getNode(
4
);
// 4
root.left = getNode(
2
);
// / \
root.right = getNode(
5
);
// 2 5
root.left.left = getNode(
7
);
// / \ / \
root.left.right = getNode(
2
);
// 7 2 2 3
root.right.left = getNode(
2
);
root.right.right = getNode(
3
);
int
x =
2
;
System.out.println(
"Sum = "
+
sumOfParentOfXUtil(root, x));
}
}
// This code is contributed by Arnab Kundu
|
n
|
438.java
| 0.5
|
class
LinkedList {
/* head node of link list */
static
LNode head;
/* Link list Node */
class
LNode
{
int
data;
LNode next, prev;
LNode(
int
d)
{
data = d;
next = prev =
null
;
}
}
/* A Binary Tree Node */
class
TNode
{
int
data;
TNode left, right;
TNode(
int
d)
{
data = d;
left = right =
null
;
}
}
/* This function counts the number of nodes in Linked List
and then calls sortedListToBSTRecur() to construct BST */
TNode sortedListToBST()
{
/*Count the number of nodes in Linked List */
int
n = countNodes(head);
/* Construct BST */
return
sortedListToBSTRecur(n);
}
/* The main function that constructs balanced BST and
returns root of it.
n --> No. of nodes in the Doubly Linked List */
TNode sortedListToBSTRecur(
int
n)
{
/* Base Case */
if
(n <=
0
)
return
null
;
/* Recursively construct the left subtree */
TNode left = sortedListToBSTRecur(n /
2
);
/* head_ref now refers to middle node,
make middle node as root of BST*/
TNode root =
new
TNode(head.data);
// Set pointer to left subtree
root.left = left;
/* Change head pointer of Linked List for parent
recursive calls */
head = head.next;
/* Recursively construct the right subtree and link it
with root. The number of nodes in right subtree is
total nodes - nodes in left subtree - 1 (for root) */
root.right = sortedListToBSTRecur(n - n /
2
-
1
);
return
root;
}
/* UTILITY FUNCTIONS */
/* A utility function that returns count of nodes in a
given Linked List */
int
countNodes(LNode head)
{
int
count =
0
;
LNode temp = head;
while
(temp !=
null
)
{
temp = temp.next;
count++;
}
return
count;
}
/* Function to insert a node at the beginging of
the Doubly Linked List */
void
push(
int
new_data)
{
/* allocate node */
LNode new_node =
new
LNode(new_data);
/* since we are adding at the begining,
prev is always NULL */
new_node.prev =
null
;
/* link the old list off the new node */
new_node.next = head;
/* change prev of head node to new node */
if
(head !=
null
)
head.prev = new_node;
/* move the head to point to the new node */
head = new_node;
}
/* Function to print nodes in a given linked list */
void
printList(LNode node)
{
while
(node !=
null
)
{
System.out.print(node.data +
" "
);
node = node.next;
}
}
/* A utility function to print preorder traversal of BST */
void
preOrder(TNode node)
{
if
(node ==
null
)
return
;
System.out.print(node.data +
" "
);
preOrder(node.left);
preOrder(node.right);
}
/* Driver program to test above functions */
public
static
void
main(String[] args) {
LinkedList llist =
new
LinkedList();
/* Let us create a sorted linked list to test the functions
Created linked list will be 7->6->5->4->3->2->1 */
llist.push(
7
);
llist.push(
6
);
llist.push(
5
);
llist.push(
4
);
llist.push(
3
);
llist.push(
2
);
llist.push(
1
);
System.out.println(
"Given Linked List "
);
llist.printList(head);
/* Convert List to BST */
TNode root = llist.sortedListToBST();
System.out.println(
""
);
System.out.println(
"Pre-Order Traversal of constructed BST "
);
llist.preOrder(root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
|
n
|
439.java
| 0.5
|
// Java Program to find maximum in arr[]
class
Test
{
static
int
arr[] = {
10
,
324
,
45
,
90
,
9808
};
// Method to find maximum in arr[]
static
int
largest()
{
int
i;
// Initialize maximum element
int
max = arr[
0
];
// Traverse array elements from second and
// compare every element with current max
for
(i =
1
; i < arr.length; i++)
if
(arr[i] > max)
max = arr[i];
return
max;
}
// Driver method
public
static
void
main(String[] args)
{
System.out.println(
"Largest in given array is "
+ largest());
}
}
|
n
|
44.java
| 0.5
|
// Java program to print BST in given range
// A binary tree node
class
Node {
int
data;
Node left, right;
Node(
int
d) {
data = d;
left = right =
null
;
}
}
class
BinaryTree {
static
Node root;
/* A function that constructs Balanced Binary Search Tree
from a sorted array */
Node sortedArrayToBST(
int
arr[],
int
start,
int
end) {
/* Base Case */
if
(start > end) {
return
null
;
}
/* Get the middle element and make it root */
int
mid = (start + end) /
2
;
Node node =
new
Node(arr[mid]);
/* Recursively construct the left subtree and make it
left child of root */
node.left = sortedArrayToBST(arr, start, mid -
1
);
/* Recursively construct the right subtree and make it
right child of root */
node.right = sortedArrayToBST(arr, mid +
1
, end);
return
node;
}
/* A utility function to print preorder traversal of BST */
void
preOrder(Node node) {
if
(node ==
null
) {
return
;
}
System.out.print(node.data +
" "
);
preOrder(node.left);
preOrder(node.right);
}
public
static
void
main(String[] args) {
BinaryTree tree =
new
BinaryTree();
int
arr[] =
new
int
[]{
1
,
2
,
3
,
4
,
5
,
6
,
7
};
int
n = arr.length;
root = tree.sortedArrayToBST(arr,
0
, n -
1
);
System.out.println(
"Preorder traversal of constructed BST"
);
tree.preOrder(root);
}
}
// This code has been contributed by Mayank Jaiswal
|
n
|
440.java
| 0.5
|
// Java program to convert BST to binary tree such that sum of
// all greater keys is added to every key
class
Node {
int
data;
Node left, right;
Node(
int
d) {
data = d;
left = right =
null
;
}
}
class
Sum {
int
sum =
0
;
}
class
BinaryTree {
static
Node root;
Sum summ =
new
Sum();
// A recursive function that traverses the given BST in reverse inorder and
// for every key, adds all greater keys to it
void
addGreaterUtil(Node node, Sum sum_ptr) {
// Base Case
if
(node ==
null
) {
return
;
}
// Recur for right subtree first so that sum of all greater
// nodes is stored at sum_ptr
addGreaterUtil(node.right, sum_ptr);
// Update the value at sum_ptr
sum_ptr.sum = sum_ptr.sum + node.data;
// Update key of this node
node.data = sum_ptr.sum;
// Recur for left subtree so that the updated sum is added
// to smaller nodes
addGreaterUtil(node.left, sum_ptr);
}
// A wrapper over addGreaterUtil(). It initializes sum and calls
// addGreaterUtil() to recursivel upodate and use value of sum
Node addGreater(Node node) {
addGreaterUtil(node, summ);
return
node;
}
// A utility function to print inorder traversal of Binary Tree
void
printInorder(Node node) {
if
(node ==
null
) {
return
;
}
printInorder(node.left);
System.out.print(node.data +
" "
);
printInorder(node.right);
}
// Driver program to test the above functions
public
static
void
main(String[] args) {
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(
5
);
tree.root.left =
new
Node(
2
);
tree.root.right =
new
Node(
13
);
System.out.println(
"Inorder traversal of given tree "
);
tree.printInorder(root);
Node node = tree.addGreater(root);
System.out.println(
""
);
System.out.println(
"Inorder traversal of modified tree "
);
tree.printInorder(node);
}
}
// This code has been contributed by Mayank Jaiswal
|
n
|
441.java
| 0.5
|
// Java program to find minimum value node in Binary Search Tree
// A binary tree node
class
Node {
int
data;
Node left, right;
Node(
int
d) {
data = d;
left = right =
null
;
}
}
class
BinaryTree {
static
Node head;
/* Given a binary search tree and a number,
inserts a new node with the given number in
the correct place in the tree. Returns the new
root pointer which the caller should then use
(the standard trick to avoid using reference
parameters). */
Node insert(Node node,
int
data) {
/* 1. If the tree is empty, return a new,
single node */
if
(node ==
null
) {
return
(
new
Node(data));
}
else
{
/* 2. Otherwise, recur down the tree */
if
(data <= node.data) {
node.left = insert(node.left, data);
}
else
{
node.right = insert(node.right, data);
}
/* return the (unchanged) node pointer */
return
node;
}
}
/* Given a non-empty binary search tree,
return the minimum data value found in that
tree. Note that the entire tree does not need
to be searched. */
int
minvalue(Node node) {
Node current = node;
/* loop down to find the leftmost leaf */
while
(current.left !=
null
) {
current = current.left;
}
return
(current.data);
}
// Driver program to test above functions
public
static
void
main(String[] args) {
BinaryTree tree =
new
BinaryTree();
Node root =
null
;
root = tree.insert(root,
4
);
tree.insert(root,
2
);
tree.insert(root,
1
);
tree.insert(root,
3
);
tree.insert(root,
6
);
tree.insert(root,
5
);
System.out.println(
"Minimum value of BST is "
+ tree.minvalue(root));
}
}
// This code is contributed by Mayank Jaiswal
|
n
|
442.java
| 0.5
|
// Java implementation to check if the given array
// can represent Level Order Traversal of Binary
// Search Tree
import
java.util.*;
class
Solution
{
// to store details of a node like
// node's data, 'min' and 'max' to obtain the
// range of values where node's left and
// right child's should lie
static
class
NodeDetails
{
int
data;
int
min, max;
};
// function to check if the given array
// can represent Level Order Traversal
// of Binary Search Tree
static
boolean
levelOrderIsOfBST(
int
arr[],
int
n)
{
// if tree is empty
if
(n ==
0
)
return
true
;
// queue to store NodeDetails
Queue<NodeDetails> q =
new
LinkedList<NodeDetails>();
// index variable to access array elements
int
i =
0
;
// node details for the
// root of the BST
NodeDetails newNode=
new
NodeDetails();
newNode.data = arr[i++];
newNode.min = Integer.MIN_VALUE;
newNode.max = Integer.MAX_VALUE;
q.add(newNode);
// until there are no more elements
// in arr[] or queue is not empty
while
(i != n && q.size() >
0
)
{
// extracting NodeDetails of a
// node from the queue
NodeDetails temp = q.peek();
q.remove();
newNode =
new
NodeDetails();
// check whether there are more elements
// in the arr[] and arr[i] can be left child
// of 'temp.data' or not
if
(i < n && (arr[i] < (
int
)temp.data &&
arr[i] > (
int
)temp.min))
{
// Create NodeDetails for newNode
/// and add it to the queue
newNode.data = arr[i++];
newNode.min = temp.min;
newNode.max = temp.data;
q.add(newNode);
}
newNode=
new
NodeDetails();
// check whether there are more elements
// in the arr[] and arr[i] can be right child
// of 'temp.data' or not
if
(i < n && (arr[i] > (
int
)temp.data &&
arr[i] < (
int
)temp.max))
{
// Create NodeDetails for newNode
/// and add it to the queue
newNode.data = arr[i++];
newNode.min = temp.data;
newNode.max = temp.max;
q.add(newNode);
}
}
// given array represents level
// order traversal of BST
if
(i == n)
return
true
;
// given array do not represent
// level order traversal of BST
return
false
;
}
// Driver code
public
static
void
main(String args[])
{
int
arr[] = {
7
,
4
,
12
,
3
,
6
,
8
,
1
,
5
,
10
};
int
n = arr.length;
if
(levelOrderIsOfBST(arr, n))
System.out.print(
"Yes"
);
else
System.out.print(
"No"
);
}
}
// This code is contributed by Arnab Kundu
|
n
|
443.java
| 0.5
|
// Java Program for finding K-th largest Node using O(1)
// extra memory and reverse Morris traversal.
class
GfG
{
static
class
Node
{
int
data;
Node left, right;
}
// helper function to create a new Node
static
Node newNode(
int
data)
{
Node temp =
new
Node();
temp.data = data;
temp.right =
null
;
temp.left =
null
;
return
temp;
}
static
Node KthLargestUsingMorrisTraversal(Node root,
int
k)
{
Node curr = root;
Node Klargest =
null
;
// count variable to keep count of visited Nodes
int
count =
0
;
while
(curr !=
null
)
{
// if right child is NULL
if
(curr.right ==
null
)
{
// first increment count and check if count = k
if
(++count == k)
Klargest = curr;
// otherwise move to the left child
curr = curr.left;
}
else
{
// find inorder successor of current Node
Node succ = curr.right;
while
(succ.left !=
null
&& succ.left != curr)
succ = succ.left;
if
(succ.left ==
null
)
{
// set left child of successor to the
// current Node
succ.left = curr;
// move current to its right
curr = curr.right;
}
// restoring the tree back to original binary
// search tree removing threaded links
else
{
succ.left =
null
;
if
(++count == k)
Klargest = curr;
// move current to its left child
curr = curr.left;
}
}
}
return
Klargest;
}
// Driver code
public
static
void
main(String[] args)
{
// Your Java Code
/* Constructed binary tree is
4
/ \
2 7
/ \ / \
1 3 6 10 */
Node root = newNode(
4
);
root.left = newNode(
2
);
root.right = newNode(
7
);
root.left.left = newNode(
1
);
root.left.right = newNode(
3
);
root.right.left = newNode(
6
);
root.right.right = newNode(
10
);
System.out.println(
"Finding K-th largest Node in BST : "
+
KthLargestUsingMorrisTraversal(root,
2
).data);
}
}
|
n
|
445.java
| 0.5
|
// Java code to find second largest element in BST
// A binary tree node
class
Node {
int
data;
Node left, right;
Node(
int
d)
{
data = d;
left = right =
null
;
}
}
class
BinarySearchTree {
// Root of BST
Node root;
// Constructor
BinarySearchTree()
{
root =
null
;
}
// function to insert new nodes
public
void
insert(
int
data)
{
this
.root =
this
.insertRec(
this
.root, data);
}
/* A utility function to insert a new node with given
key in BST */
Node insertRec(Node node,
int
data)
{
/* If the tree is empty, return a new node */
if
(node ==
null
) {
this
.root =
new
Node(data);
return
this
.root;
}
/* Otherwise, recur down the tree */
if
(data < node.data) {
node.left =
this
.insertRec(node.left, data);
}
else
{
node.right =
this
.insertRec(node.right, data);
}
return
node;
}
// class that stores the value of count
public
class
count {
int
c =
0
;
}
// Function to find 2nd largest element
void
secondLargestUtil(Node node, count C)
{
// Base cases, the second condition is important to
// avoid unnecessary recursive calls
if
(node ==
null
|| C.c >=
2
)
return
;
// Follow reverse inorder traversal so that the
// largest element is visited first
this
.secondLargestUtil(node.right, C);
// Increment count of visited nodes
C.c++;
// If c becomes k now, then this is the 2nd largest
if
(C.c ==
2
) {
System.out.print(
"2nd largest element is "
+
node.data);
return
;
}
// Recur for left subtree
this
.secondLargestUtil(node.left, C);
}
// Function to find 2nd largest element
void
secondLargest(Node node)
{
// object of class count
count C =
new
count();
this
.secondLargestUtil(
this
.root, C);
}
// Driver function
public
static
void
main(String[] args)
{
BinarySearchTree tree =
new
BinarySearchTree();
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
tree.insert(
50
);
tree.insert(
30
);
tree.insert(
20
);
tree.insert(
40
);
tree.insert(
70
);
tree.insert(
60
);
tree.insert(
80
);
tree.secondLargest(tree.root);
}
}
// This code is contributed by Kamal Rawal
|
n
|
446.java
| 0.5
|
// Java program to find k'th largest element in BST
import
java.util.*;
class
GfG {
// A BST node
static
class
Node
{
int
key;
Node left, right;
}
// A function to find
static
int
KSmallestUsingMorris(Node root,
int
k)
{
// Count to iterate over elements till we
// get the kth smallest number
int
count =
0
;
int
ksmall = Integer.MIN_VALUE;
// store the Kth smallest
Node curr = root;
// to store the current node
while
(curr !=
null
)
{
// Like Morris traversal if current does
// not have left child rather than printing
// as we did in inorder, we will just
// increment the count as the number will
// be in an increasing order
if
(curr.left ==
null
)
{
count++;
// if count is equal to K then we found the
// kth smallest, so store it in ksmall
if
(count==k)
ksmall = curr.key;
// go to current's right child
curr = curr.right;
}
else
{
// we create links to Inorder Successor and
// count using these links
Node pre = curr.left;
while
(pre.right !=
null
&& pre.right != curr)
pre = pre.right;
// building links
if
(pre.right==
null
)
{
//link made to Inorder Successor
pre.right = curr;
curr = curr.left;
}
// While breaking the links in so made temporary
// threaded tree we will check for the K smallest
// condition
else
{
// Revert the changes made in if part (break link
// from the Inorder Successor)
pre.right =
null
;
count++;
// If count is equal to K then we found
// the kth smallest and so store it in ksmall
if
(count==k)
ksmall = curr.key;
curr = curr.right;
}
}
}
return
ksmall;
//return the found value
}
// A utility function to create a new BST node
static
Node newNode(
int
item)
{
Node temp =
new
Node();
temp.key = item;
temp.left =
null
;
temp.right =
null
;
return
temp;
}
/* A utility function to insert a new node with given key in BST */
static
Node insert(Node node,
int
key)
{
/* If the tree is empty, return a new node */
if
(node ==
null
)
return
newNode(key);
/* Otherwise, recur down the tree */
if
(key < node.key)
node.left = insert(node.left, key);
else
if
(key > node.key)
node.right = insert(node.right, key);
/* return the (unchanged) node pointer */
return
node;
}
// Driver Program to test above functions
public
static
void
main(String[] args)
{
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
Node root =
null
;
root = insert(root,
50
);
insert(root,
30
);
insert(root,
20
);
insert(root,
40
);
insert(root,
70
);
insert(root,
60
);
insert(root,
80
);
for
(
int
k=
1
; k<=
7
; k++)
System.out.print(KSmallestUsingMorris(root, k) +
" "
);
}
}
|
n
|
447.java
| 0.5
|
// Java program to check if a given array is sorted
// or not.
class
GFG {
// Function that returns true if array is Inorder
// traversal of any Binary Search Tree or not.
static
boolean
isInorder(
int
[] arr,
int
n) {
// Array has one or no element
if
(n ==
0
|| n ==
1
) {
return
true
;
}
for
(
int
i =
1
; i < n; i++)
// Unsorted pair found
{
if
(arr[i -
1
] > arr[i]) {
return
false
;
}
}
// No unsorted pair found
return
true
;
}
// Drivers code
public
static
void
main(String[] args) {
int
arr[] = {
19
,
23
,
25
,
30
,
45
};
int
n = arr.length;
if
(isInorder(arr, n)) {
System.out.println(
"Yes"
);
}
else
{
System.out.println(
"Non"
);
}
}
}
//This code is contributed by 29AjayKumar
|
n
|
449.java
| 0.5
|
// Java code to find largest three elements
// in an array
class
PrintLargest
{
/* Function to print three largest elements */
static
void
print3largest(
int
arr[],
int
arr_size)
{
int
i, first, second, third;
/* There should be atleast three elements */
if
(arr_size <
3
)
{
System.out.print(
" Invalid Input "
);
return
;
}
third = first = second = Integer.MIN_VALUE;
for
(i =
0
; i < arr_size ; i ++)
{
/* If current element is greater than
first*/
if
(arr[i] > first)
{
third = second;
second = first;
first = arr[i];
}
/* If arr[i] is in between first and
second then update second */
else
if
(arr[i] > second)
{
third = second;
second = arr[i];
}
else
if
(arr[i] > third)
third = arr[i];
}
System.out.println(
"Three largest elements are "
+
first +
" "
+ second +
" "
+ third);
}
/* Driver program to test above function*/
public
static
void
main (String[] args)
{
int
arr[] = {
12
,
13
,
1
,
10
,
34
,
1
};
int
n = arr.length;
print3largest(arr, n);
}
}
/*This code is contributed by Prakriti Gupta
and edited by Ayush Singla(@ayusin51)*/
|
n
|
45.java
| 0.5
|
// Java implementation to count pairs from two
// BSTs whose sum is equal to a given value x
import
java.util.Stack;
public
class
GFG {
// structure of a node of BST
static
class
Node {
int
data;
Node left, right;
// constructor
public
Node(
int
data) {
this
.data = data;
left =
null
;
right =
null
;
}
}
static
Node root1;
static
Node root2;
// function to count pairs from two BSTs
// whose sum is equal to a given value x
static
int
countPairs(Node root1, Node root2,
int
x)
{
// if either of the tree is empty
if
(root1 ==
null
|| root2 ==
null
)
return
0
;
// stack 'st1' used for the inorder
// traversal of BST 1
// stack 'st2' used for the reverse
// inorder traversal of BST 2
//stack<Node*> st1, st2;
Stack<Node> st1 =
new
Stack<>();
Stack<Node> st2 =
new
Stack<>();
Node top1, top2;
int
count =
0
;
// the loop will break when either of two
// traversals gets completed
while
(
true
) {
// to find next node in inorder
// traversal of BST 1
while
(root1 !=
null
) {
st1.push(root1);
root1 = root1.left;
}
// to find next node in reverse
// inorder traversal of BST 2
while
(root2 !=
null
) {
st2.push(root2);
root2 = root2.right;
}
// if either gets empty then corresponding
// tree traversal is completed
if
(st1.empty() || st2.empty())
break
;
top1 = st1.peek();
top2 = st2.peek();
// if the sum of the node's is equal to 'x'
if
((top1.data + top2.data) == x) {
// increment count
count++;
// pop nodes from the respective stacks
st1.pop();
st2.pop();
// insert next possible node in the
// respective stacks
root1 = top1.right;
root2 = top2.left;
}
// move to next possible node in the
// inoder traversal of BST 1
else
if
((top1.data + top2.data) < x) {
st1.pop();
root1 = top1.right;
}
// move to next possible node in the
// reverse inoder traversal of BST 2
else
{
st2.pop();
root2 = top2.left;
}
}
// required count of pairs
return
count;
}
// Driver program to test above
public
static
void
main(String args[])
{
// formation of BST 1
root1 =
new
Node(
5
);
/* 5 */
root1.left =
new
Node(
3
);
/* / \ */
root1.right =
new
Node(
7
);
/* 3 7 */
root1.left.left =
new
Node(
2
);
/* / \ / \ */
root1.left.right =
new
Node(
4
);
/* 2 4 6 8 */
root1.right.left =
new
Node(
6
);
root1.right.right =
new
Node(
8
);
// formation of BST 2
root2 =
new
Node(
10
);
/* 10 */
root2.left =
new
Node(
6
);
/* / \ */
root2.right =
new
Node(
15
);
/* 6 15 */
root2.left.left =
new
Node(
3
);
/* / \ / \ */
root2.left.right =
new
Node(
8
);
/* 3 8 11 18 */
root2.right.left =
new
Node(
11
);
root2.right.right =
new
Node(
18
);
int
x =
16
;
System.out.println(
"Pairs = "
+ countPairs(root1, root2, x));
}
}
// This code is contributed by Sumit Ghosh
|
n
|
451.java
| 0.5
|
// A Java program to remove BST
// keys outside the given range
import
java.math.BigDecimal;
import
java.util.ArrayList;
import
java.util.Arrays;
import
java.util.List;
import
java.util.Scanner;
class
Node
{
int
key;
Node left;
Node right;
}
class
GFG
{
// Removes all nodes having value
// outside the given range and
// returns the root of modified tree
private
static
Node removeOutsideRange(Node root,
int
min,
int
max)
{
// BASE CASE
if
(root ==
null
)
{
return
null
;
}
// FIRST FIX THE LEFT AND
// RIGHT SUBTREE OF ROOT
root.left = removeOutsideRange(root.left,
min, max);
root.right = removeOutsideRange(root.right,
min, max);
// NOW FIX THE ROOT. THERE ARE
// TWO POSSIBLE CASES FOR THE ROOT
// 1. a) Root's key is smaller than
// min value(root is not in range)
if
(root.key < min)
{
Node rchild = root.right;
root =
null
;
return
rchild;
}
// 1. b) Root's key is greater than
// max value (Root is not in range)
if
(root.key > max)
{
Node lchild = root.left;
root =
null
;
return
lchild;
}
// 2. Root in range
return
root;
}
public
static
Node newNode(
int
num)
{
Node temp =
new
Node();
temp.key = num;
temp.left =
null
;
temp.right =
null
;
return
temp;
}
public
static
Node insert(Node root,
int
key)
{
if
(root ==
null
)
{
return
newNode(key);
}
if
(root.key > key)
{
root.left = insert(root.left, key);
}
else
{
root.right = insert(root.right, key);
}
return
root;
}
private
static
void
inorderTraversal(Node root)
{
if
(root !=
null
)
{
inorderTraversal(root.left);
System.out.print(root.key +
" "
);
inorderTraversal(root.right);
}
}
// Driver code
public
static
void
main(String[] args)
{
Node root =
null
;
root = insert(root,
6
);
root = insert(root, -
13
);
root = insert(root,
14
);
root = insert(root, -
8
);
root = insert(root,
15
);
root = insert(root,
13
);
root = insert(root,
7
);
System.out.print(
"Inorder Traversal of "
+
"the given tree is: "
);
inorderTraversal(root);
root = removeOutsideRange(root, -
10
,
13
);
System.out.print(
"\nInorder traversal of "
+
"the modified tree: "
);
inorderTraversal(root);
}
}
// This code is contributed
// by Divya
|
n
|
452.java
| 0.5
|
// Java code to find a pair with given sum
// in a Balanced BST
import
java.util.ArrayList;
// A binary tree node
class
Node {
int
data;
Node left, right;
Node(
int
d)
{
data = d;
left = right =
null
;
}
}
class
BinarySearchTree {
// Root of BST
Node root;
// Constructor
BinarySearchTree()
{
root =
null
;
}
// Inorder traversal of the tree
void
inorder()
{
inorderUtil(
this
.root);
}
// Utility function for inorder traversal of the tree
void
inorderUtil(Node node)
{
if
(node ==
null
)
return
;
inorderUtil(node.left);
System.out.print(node.data +
" "
);
inorderUtil(node.right);
}
// This method mainly calls insertRec()
void
insert(
int
key)
{
root = insertRec(root, key);
}
/* A recursive function to insert a new key in BST */
Node insertRec(Node root,
int
data)
{
/* If the tree is empty, return a new node */
if
(root ==
null
) {
root =
new
Node(data);
return
root;
}
/* Otherwise, recur down the tree */
if
(data < root.data)
root.left = insertRec(root.left, data);
else
if
(data > root.data)
root.right = insertRec(root.right, data);
return
root;
}
// Method that adds values of given BST into ArrayList
// and hence returns the ArrayList
ArrayList<Integer> treeToList(Node node, ArrayList<Integer>
list)
{
// Base Case
if
(node ==
null
)
return
list;
treeToList(node.left, list);
list.add(node.data);
treeToList(node.right, list);
return
list;
}
// method that checks if there is a pair present
boolean
isPairPresent(Node node,
int
target)
{
// This list a1 is passed as an argument
// in treeToList method
// which is later on filled by the values of BST
ArrayList<Integer> a1 =
new
ArrayList<>();
// a2 list contains all the values of BST
// returned by treeToList method
ArrayList<Integer> a2 = treeToList(node, a1);
int
start =
0
;
// Starting index of a2
int
end = a2.size() -
1
;
// Ending index of a2
while
(start < end) {
if
(a2.get(start) + a2.get(end) == target)
// Target Found!
{
System.out.println(
"Pair Found: "
+ a2.get(start) +
" + "
+ a2.get(end) +
" "
+
"= "
+ target);
return
true
;
}
if
(a2.get(start) + a2.get(end) > target)
// decrements end
{
end--;
}
if
(a2.get(start) + a2.get(end) < target)
// increments start
{
start++;
}
}
System.out.println(
"No such values are found!"
);
return
false
;
}
// Driver function
public
static
void
main(String[] args)
{
BinarySearchTree tree =
new
BinarySearchTree();
/*
15
/ \
10 20
/ \ / \
8 12 16 25 */
tree.insert(
15
);
tree.insert(
10
);
tree.insert(
20
);
tree.insert(
8
);
tree.insert(
12
);
tree.insert(
16
);
tree.insert(
25
);
tree.isPairPresent(tree.root,
33
);
}
}
// This code is contributed by Kamal Rawal
|
n
|
453.java
| 0.5
|
// Java program to find maximum element in the path
// between two Nodes of Binary Search Tree.
class
Solution
{
static
class
Node
{
Node left, right;
int
data;
}
// Create and return a pointer of new Node.
static
Node createNode(
int
x)
{
Node p =
new
Node();
p . data = x;
p . left = p . right =
null
;
return
p;
}
// Insert a new Node in Binary Search Tree.
static
void
insertNode( Node root,
int
x)
{
Node p = root, q =
null
;
while
(p !=
null
)
{
q = p;
if
(p . data < x)
p = p . right;
else
p = p . left;
}
if
(q ==
null
)
p = createNode(x);
else
{
if
(q . data < x)
q . right = createNode(x);
else
q . left = createNode(x);
}
}
// Return the maximum element between a Node
// and its given ancestor.
static
int
maxelpath(Node q,
int
x)
{
Node p = q;
int
mx = -
1
;
// Traversing the path between ansector and
// Node and finding maximum element.
while
(p . data != x)
{
if
(p . data > x)
{
mx = Math.max(mx, p . data);
p = p . left;
}
else
{
mx = Math.max(mx, p . data);
p = p . right;
}
}
return
Math.max(mx, x);
}
// Return maximum element in the path between
// two given Node of BST.
static
int
maximumElement( Node root,
int
x,
int
y)
{
Node p = root;
// Finding the LCA of Node x and Node y
while
((x < p . data && y < p . data) ||
(x > p . data && y > p . data))
{
// Checking if both the Node lie on the
// left side of the parent p.
if
(x < p . data && y < p . data)
p = p . left;
// Checking if both the Node lie on the
// right side of the parent p.
else
if
(x > p . data && y > p . data)
p = p . right;
}
// Return the maximum of maximum elements occur
// in path from ancestor to both Node.
return
Math.max(maxelpath(p, x), maxelpath(p, y));
}
// Driver Code
public
static
void
main(String args[])
{
int
arr[] = {
18
,
36
,
9
,
6
,
12
,
10
,
1
,
8
};
int
a =
1
, b =
10
;
int
n =arr.length;
// Creating the root of Binary Search Tree
Node root = createNode(arr[
0
]);
// Inserting Nodes in Binary Search Tree
for
(
int
i =
1
; i < n; i++)
insertNode(root, arr[i]);
System.out.println( maximumElement(root, a, b) );
}
}
//contributed by Arnab Kundu
|
n
|
454.java
| 0.5
|
// Java program to find pairs with given sum such
// that one element of pair exists in one BST and
// other in other BST.
import
java.util.*;
class
solution
{
// A binary Tree node
static
class
Node
{
int
data;
Node left, right;
};
// A utility function to create a new BST node
// with key as given num
static
Node newNode(
int
num)
{
Node temp =
new
Node();
temp.data = num;
temp.left = temp.right =
null
;
return
temp;
}
// A utility function to insert a given key to BST
static
Node insert(Node root,
int
key)
{
if
(root ==
null
)
return
newNode(key);
if
(root.data > key)
root.left = insert(root.left, key);
else
root.right = insert(root.right, key);
return
root;
}
// store storeInorder traversal in auxiliary array
static
void
storeInorder(Node ptr, Vector<Integer> vect)
{
if
(ptr==
null
)
return
;
storeInorder(ptr.left, vect);
vect.add(ptr.data);
storeInorder(ptr.right, vect);
}
// Function to find pair for given sum in different bst
// vect1.get() -. stores storeInorder traversal of first bst
// vect2.get() -. stores storeInorder traversal of second bst
static
void
pairSumUtil(Vector<Integer> vect1, Vector<Integer> vect2,
int
sum)
{
// Initialize two indexes to two different corners
// of two Vectors.
int
left =
0
;
int
right = vect2.size() -
1
;
// find pair by moving two corners.
while
(left < vect1.size() && right >=
0
)
{
// If we found a pair
if
(vect1.get(left) + vect2.get(right) == sum)
{
System.out.print(
"("
+vect1.get(left) +
", "
+ vect2.get(right) +
"), "
);
left++;
right--;
}
// If sum is more, move to higher value in
// first Vector.
else
if
(vect1.get(left) + vect2.get(right) < sum)
left++;
// If sum is less, move to lower value in
// second Vector.
else
right--;
}
}
// Prints all pairs with given "sum" such that one
// element of pair is in tree with root1 and other
// node is in tree with root2.
static
void
pairSum(Node root1, Node root2,
int
sum)
{
// Store inorder traversals of two BSTs in two
// Vectors.
Vector<Integer> vect1=
new
Vector<Integer>(), vect2=
new
Vector<Integer>();
storeInorder(root1, vect1);
storeInorder(root2, vect2);
// Now the problem reduces to finding a pair
// with given sum such that one element is in
// vect1 and other is in vect2.
pairSumUtil(vect1, vect2, sum);
}
// Driver program to run the case
public
static
void
main(String args[])
{
// first BST
Node root1 =
null
;
root1 = insert(root1,
8
);
root1 = insert(root1,
10
);
root1 = insert(root1,
3
);
root1 = insert(root1,
6
);
root1 = insert(root1,
1
);
root1 = insert(root1,
5
);
root1 = insert(root1,
7
);
root1 = insert(root1,
14
);
root1 = insert(root1,
13
);
// second BST
Node root2 =
null
;
root2 = insert(root2,
5
);
root2 = insert(root2,
18
);
root2 = insert(root2,
2
);
root2 = insert(root2,
1
);
root2 = insert(root2,
3
);
root2 = insert(root2,
4
);
int
sum =
10
;
pairSum(root1, root2, sum);
}
}
//contributed by Arnab Kundu
|
n
|
455.java
| 0.5
|
// Java code to add all greater values to
// every node in a given BST
// A binary tree node
class
Node {
int
data;
Node left, right;
Node(
int
d)
{
data = d;
left = right =
null
;
}
}
class
BinarySearchTree {
// Root of BST
Node root;
// Constructor
BinarySearchTree()
{
root =
null
;
}
// Inorder traversal of the tree
void
inorder()
{
inorderUtil(
this
.root);
}
// Utility function for inorder traversal of
// the tree
void
inorderUtil(Node node)
{
if
(node ==
null
)
return
;
inorderUtil(node.left);
System.out.print(node.data +
" "
);
inorderUtil(node.right);
}
// adding new node
public
void
insert(
int
data)
{
this
.root =
this
.insertRec(
this
.root, data);
}
/* A utility function to insert a new node with
given data in BST */
Node insertRec(Node node,
int
data)
{
/* If the tree is empty, return a new node */
if
(node ==
null
) {
this
.root =
new
Node(data);
return
this
.root;
}
/* Otherwise, recur down the tree */
if
(data <= node.data) {
node.left =
this
.insertRec(node.left, data);
}
else
{
node.right =
this
.insertRec(node.right, data);
}
return
node;
}
// This class initialises the value of sum to 0
public
class
Sum {
int
sum =
0
;
}
// Recursive function to add all greater values in
// every node
void
modifyBSTUtil(Node node, Sum S)
{
// Base Case
if
(node ==
null
)
return
;
// Recur for right subtree
this
.modifyBSTUtil(node.right, S);
// Now *sum has sum of nodes in right subtree, add
// root->data to sum and update root->data
S.sum = S.sum + node.data;
node.data = S.sum;
// Recur for left subtree
this
.modifyBSTUtil(node.left, S);
}
// A wrapper over modifyBSTUtil()
void
modifyBST(Node node)
{
Sum S =
new
Sum();
this
.modifyBSTUtil(node, S);
}
// Driver Function
public
static
void
main(String[] args)
{
BinarySearchTree tree =
new
BinarySearchTree();
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
tree.insert(
50
);
tree.insert(
30
);
tree.insert(
20
);
tree.insert(
40
);
tree.insert(
70
);
tree.insert(
60
);
tree.insert(
80
);
tree.modifyBST(tree.root);
// print inoder tarversal of the modified BST
tree.inorder();
}
}
// This code is contributed by Kamal Rawal
|
n
|
456.java
| 0.5
|
// Java program to find efficient
// solution for the network
import
java.util.*;
class
GFG {
// number of houses and number
// of pipes
static
int
n, p;
// Array rd stores the
// ending vertex of pipe
static
int
rd[] =
new
int
[
1100
];
// Array wd stores the value
// of diameters between two pipes
static
int
wt[] =
new
int
[
1100
];
// Array cd stores the
// starting end of pipe
static
int
cd[] =
new
int
[
1100
];
// arraylist a, b, c are used
// to store the final output
static
List <Integer> a =
new
ArrayList<Integer>();
static
List <Integer> b =
new
ArrayList<Integer>();
static
List <Integer> c =
new
ArrayList<Integer>();
static
int
ans;
static
int
dfs(
int
w)
{
if
(cd[w] ==
0
)
return
w;
if
(wt[w] < ans)
ans = wt[w];
return
dfs(cd[w]);
}
// Function to perform calculations.
static
void
solve(
int
arr[][])
{
int
i =
0
;
while
(i < p)
{
int
q = arr[i][
0
];
int
h = arr[i][
1
];
int
t = arr[i][
2
];
cd[q] = h;
wt[q] = t;
rd[h] = q;
i++;
}
a=
new
ArrayList<Integer>();
b=
new
ArrayList<Integer>();
c=
new
ArrayList<Integer>();
for
(
int
j =
1
; j <= n; ++j)
/*If a pipe has no ending vertex
but has starting vertex i.e is
an outgoing pipe then we need
to start DFS with this vertex.*/
if
(rd[j] ==
0
&& cd[j]>
0
) {
ans =
1000000000
;
int
w = dfs(j);
// We put the details of
// component in final output
// array
a.add(j);
b.add(w);
c.add(ans);
}
System.out.println(a.size());
for
(
int
j =
0
; j < a.size(); ++j)
System.out.println(a.get(j) +
" "
+ b.get(j) +
" "
+ c.get(j));
}
// main function
public
static
void
main(String args[])
{
n =
9
;
p =
6
;
// set the value of the araray
// to zero
for
(
int
i =
0
; i <
1100
; i++)
rd[i] = cd[i] = wt[i] =
0
;
int
arr[][] = { {
7
,
4
,
98
},
{
5
,
9
,
72
},
{
4
,
6
,
10
},
{
2
,
8
,
22
},
{
9
,
7
,
17
},
{
3
,
1
,
66
} };
solve(arr);
}
}
// This code is contributed by Arnab Kundu
|
n
|
461.java
| 0.5
|
// Java program to find maximum number of
// thieves caught
import
java.util.*;
import
java.io.*;
class
GFG
{
// Returns maximum number of thieves
// that can be caught.
static
int
policeThief(
char
arr[],
int
n,
int
k)
{
int
res =
0
;
ArrayList<Integer> thi =
new
ArrayList<Integer>();
ArrayList<Integer> pol =
new
ArrayList<Integer>();
// store indices in the ArrayList
for
(
int
i =
0
; i < n; i++) {
if
(arr[i] ==
'P'
)
pol.add(i);
else
if
(arr[i] ==
'T'
)
thi.add(i);
}
// track lowest current indices of
// thief: thi[l], police: pol[r]
int
l =
0
, r =
0
;
while
(l < thi.size() && r < pol.size()) {
// can be caught
if
(Math.abs(thi.get(l) - pol.get(r)) <= k) {
res++;
l++;
r++;
}
// increment the minimum index
else
if
(thi.get(l) < pol.get(r))
l++;
else
r++;
}
return
res;
}
// Driver program
public
static
void
main(String args[])
{
int
k, n;
char
arr1[] =
new
char
[] {
'P'
,
'T'
,
'T'
,
'P'
,
'T'
};
k =
2
;
n = arr1.length;
System.out.println(
"Maximum thieves caught: "
+policeThief(arr1, n, k));
char
arr2[] =
new
char
[] {
'T'
,
'T'
,
'P'
,
'P'
,
'T'
,
'P'
};
k =
2
;
n = arr2.length;
System.out.println(
"Maximum thieves caught: "
+policeThief(arr2, n, k));
char
arr3[] =
new
char
[]{
'P'
,
'T'
,
'P'
,
'T'
,
'T'
,
'P'
};
k =
3
;
n = arr3.length;
System.out.println(
"Maximum thieves caught: "
+policeThief(arr3, n, k));
}
}
/* This code is contributed by Danish kaleem */
|
n
|
462.java
| 0.5
|
// Java program to find maximum product of
// a subset.
class
GFG {
static
int
minProductSubset(
int
a[],
int
n)
{
if
(n ==
1
)
return
a[
0
];
// Find count of negative numbers,
// count of zeros, maximum valued
// negative number, minimum valued
// positive number and product of
// non-zero numbers
int
negmax = Integer.MIN_VALUE;
int
posmin = Integer.MAX_VALUE;
int
count_neg =
0
, count_zero =
0
;
int
product =
1
;
for
(
int
i =
0
; i < n; i++)
{
// if number is zero,count it
// but dont multiply
if
(a[i] ==
0
){
count_zero++;
continue
;
}
// count the negetive numbers
// and find the max negetive number
if
(a[i] <
0
)
{
count_neg++;
negmax = Math.max(negmax, a[i]);
}
// find the minimum positive number
if
(a[i] >
0
&& a[i] < posmin)
posmin = a[i];
product *= a[i];
}
// if there are all zeroes
// or zero is present but no
// negetive number is present
if
(count_zero == n ||
(count_neg ==
0
&& count_zero >
0
))
return
0
;
// If there are all positive
if
(count_neg ==
0
)
return
posmin;
// If there are even number except
// zero of negative numbers
if
(count_neg %
2
==
0
&& count_neg !=
0
)
{
// Otherwise result is product of
// all non-zeros divided by maximum
// valued negative.
product = product / negmax;
}
return
product;
}
// main function
public
static
void
main(String[] args)
{
int
a[] = { -
1
, -
1
, -
2
,
4
,
3
};
int
n =
5
;
System.out.println(minProductSubset(a, n));
}
}
// This code is contributed by Arnab Kundu.
|
n
|
469.java
| 0.5
|
// Java program to find maximum product of
// a subset.
class
GFG {
static
int
maxProductSubset(
int
a[],
int
n) {
if
(n ==
1
) {
return
a[
0
];
}
// Find count of negative numbers, count
// of zeros, maximum valued negative number
// and product of non-zero numbers
int
max_neg = Integer.MIN_VALUE;
int
count_neg =
0
, count_zero =
0
;
int
prod =
1
;
for
(
int
i =
0
; i < n; i++) {
// If number is 0, we don't
// multiply it with product.
if
(a[i] ==
0
) {
count_zero++;
continue
;
}
// Count negatives and keep
// track of maximum valued negative.
if
(a[i] <
0
) {
count_neg++;
max_neg = Math.max(max_neg, a[i]);
}
prod = prod * a[i];
}
// If there are all zeros
if
(count_zero == n) {
return
0
;
}
// If there are odd number of
// negative numbers
if
(count_neg %
2
==
1
) {
// Exceptional case: There is only
// negative and all other are zeros
if
(count_neg ==
1
&& count_zero >
0
&& count_zero + count_neg == n) {
return
0
;
}
// Otherwise result is product of
// all non-zeros divided by maximum
// valued negative.
prod = prod / max_neg;
}
return
prod;
}
// Driver code
public
static
void
main(String[] args) {
int
a[] = {-
1
, -
1
, -
2
,
4
,
3
};
int
n = a.length;
System.out.println(maxProductSubset(a, n));
}
}
/* This JAVA code is contributed by Rajput-Ji*/
|
n
|
470.java
| 0.5
|
// Java program to minimize the
// cost of array minimization
import
java.util.Arrays;
public
class
GFG {
// Returns minimum possible
// sum in array B[]
static
int
minSum(
int
[] A,
int
n) {
int
min_val = Arrays.stream(A).min().getAsInt();
return
(min_val * (n -
1
));
}
// Driver Code
static
public
void
main(String[] args) {
int
[] A = {
3
,
6
,
2
,
8
,
7
,
5
};
int
n = A.length;
System.out.println((minSum(A, n)));
}
}
// This code is contributed by Rajput-Ji
|
n
|
479.java
| 0.5
|
// Java program to make GCD
// of array a mutiple of k.
import
java.io.*;
class
GFG
{
static
int
MinOperation(
int
a[],
int
n,
int
k)
{
int
result =
0
;
for
(
int
i =
0
; i < n; ++i)
{
// If array value is not 1
// and it is greater than k
// then we can increase the
// or decrease the remainder
// obtained by dividing k
// from the ith value of array
// so that we get the number
// which is either closer to k
// or its multiple
if
(a[i] !=
1
&& a[i] > k)
{
result = result +
Math.min(a[i] % k,
k - a[i] % k);
}
else
{
// Else we only have one
// choice which is to
// increment the value
// to make equal to k
result = result + k - a[i];
}
}
return
result;
}
// Driver code
public
static
void
main (String[] args)
{
int
arr[] = {
4
,
5
,
6
};
int
n = arr.length;
int
k =
5
;
System.out.println(MinOperation(arr, n, k));
}
}
// This code is contributed
// by akt_mit
|
n
|
481.java
| 0.5
|
// JAVA Code for Find maximum sum possible
// equal sum of three stacks
class
GFG {
// Returns maximum possible equal sum of three
// stacks with removal of top elements allowed
public
static
int
maxSum(
int
stack1[],
int
stack2[],
int
stack3[],
int
n1,
int
n2,
int
n3)
{
int
sum1 =
0
, sum2 =
0
, sum3 =
0
;
// Finding the initial sum of stack1.
for
(
int
i=
0
; i < n1; i++)
sum1 += stack1[i];
// Finding the initial sum of stack2.
for
(
int
i=
0
; i < n2; i++)
sum2 += stack2[i];
// Finding the initial sum of stack3.
for
(
int
i=
0
; i < n3; i++)
sum3 += stack3[i];
// As given in question, first element is top
// of stack..
int
top1 =
0
, top2 =
0
, top3 =
0
;
int
ans =
0
;
while
(
true
)
{
// If any stack is empty
if
(top1 == n1 || top2 == n2 || top3 == n3)
return
0
;
// If sum of all three stack are equal.
if
(sum1 == sum2 && sum2 == sum3)
return
sum1;
// Finding the stack with maximum sum and
// removing its top element.
if
(sum1 >= sum2 && sum1 >= sum3)
sum1 -= stack1[top1++];
else
if
(sum2 >= sum3 && sum2 >= sum3)
sum2 -= stack2[top2++];
else
if
(sum3 >= sum2 && sum3 >= sum1)
sum3 -= stack3[top3++];
}
}
/* Driver program to test above function */
public
static
void
main(String[] args)
{
int
stack1[] = {
3
,
2
,
1
,
1
,
1
};
int
stack2[] = {
4
,
3
,
2
};
int
stack3[] = {
1
,
1
,
4
,
1
};
int
n1 = stack1.length;
int
n2 = stack2.length;
int
n3 = stack3.length;
System.out.println(maxSum(stack1, stack2,
stack3, n1, n2, n3));
}
}
// This code is contributed by Arnav Kr. Mandal.
|
n
|
494.java
| 0.5
|
// Java program to divide n integers
// in two groups such that absolute
// difference of their sum is minimum
import
java.io.*;
import
java.util.*;
class
GFG
{
// To print vector along size
static
void
printVector(Vector<Integer> v)
{
// Print vector size
System.out.println(v.size());
// Print vector elements
for
(
int
i =
0
; i < v.size(); i++)
System.out.print(v.get(i) +
" "
);
System.out.println();
}
// To divide n in two groups such that
// absolute difference of their sum is
// minimum
static
void
findTwoGroup(
int
n)
{
// Find sum of all elements upto n
int
sum = n * (n +
1
) /
2
;
// Sum of elements of group1
int
group1Sum = sum /
2
;
Vector<Integer> group1 =
new
Vector<Integer>();
Vector<Integer> group2 =
new
Vector<Integer>();
for
(
int
i = n; i >
0
; i--) {
// If sum is greater then or equal
// to 0 include i in group1
// otherwise include in group2
if
(group1Sum - i >=
0
) {
group1.add(i);
// Decrease sum of group1
group1Sum -= i;
}
else
{
group2.add(i);
}
}
// Print both the groups
printVector(group1);
printVector(group2);
}
// Driver code
public
static
void
main (String[] args)
{
int
n =
5
;
findTwoGroup(n);
}
}
// This code is contributed by Gitanjali.
|
n
|
496.java
| 0.5
|
// Java program to find minimum cost
// to reduce array size to 1,
import
java.lang.*;
public
class
GFG {
// function to calculate the
// minimum cost
static
int
cost(
int
[]a,
int
n)
{
int
min = a[
0
];
// find the minimum using
// for loop
for
(
int
i =
1
; i< a.length; i++)
{
if
(a[i] < min)
min = a[i];
}
// Minimum cost is n-1 multiplied
// with minimum element.
return
(n -
1
) * min;
}
// driver program to test the
// above function.
static
public
void
main (String[] args)
{
int
[]a = {
4
,
3
,
2
};
int
n = a.length;
System.out.println(cost(a, n));
}
}
// This code is contributed by parashar.
|
n
|
500.java
| 0.5
|
// Java program to find smallest
// number to find smallest number
// with N as sum of digits and
// divisible by 10^N.
import
java.io.*;
class
GFG
{
static
void
digitsNum(
int
N)
{
// If N = 0 the string will be 0
if
(N ==
0
)
System.out.println(
"0"
);
// If n is not perfectly divisible
// by 9 output the remainder
if
(N %
9
!=
0
)
System.out.print((N %
9
));
// Print 9 N/9 times
for
(
int
i =
1
; i <= (N /
9
); ++i)
System.out.print(
"9"
);
// Append N zero's to the number so
// as to make it divisible by 10^N
for
(
int
i =
1
; i <= N; ++i)
System.out.print(
"0"
);
System.out.print(
""
);
}
// Driver Code
public
static
void
main (String[] args)
{
int
N =
5
;
System.out.print(
"The number is : "
);
digitsNum(N);
}
}
// This code is contributed by vt_m
|
n
|
506.java
| 0.5
|
// Java program to find the smallest number that can be
// formed from given sum of digits and number of digits
class
GFG
{
// Function to print the smallest possible number with digit sum 's'
// and 'm' number of digits
static
void
findSmallest(
int
m,
int
s)
{
// If sum of digits is 0, then a number is possible
// only if number of digits is 1
if
(s ==
0
)
{
System.out.print(m ==
1
?
"Smallest number is 0"
:
"Not possible"
);
return
;
}
// Sum greater than the maximum possible sum
if
(s >
9
*m)
{
System.out.println(
"Not possible"
);
return
;
}
// Create an array to store digits of result
int
[] res =
new
int
[m];
// deduct sum by one to account for cases later
// (There must be 1 left for the most significant
// digit)
s -=
1
;
// Fill last m-1 digits (from right to left)
for
(
int
i=m-
1
; i>
0
; i--)
{
// If sum is still greater than 9,
// digit must be 9
if
(s >
9
)
{
res[i] =
9
;
s -=
9
;
}
else
{
res[i] = s;
s =
0
;
}
}
// Whatever is left should be the most significant
// digit
res[
0
] = s +
1
;
// The initially subtracted 1 is
// incorporated here
System.out.print(
"Smallest number is "
);
for
(
int
i=
0
; i<m; i++)
System.out.print(res[i]);
}
// driver program
public
static
void
main (String[] args)
{
int
s =
9
, m =
2
;
findSmallest(m, s);
}
}
// Contributed by Pramod Kumar
|
n
|
507.java
| 0.5
|
// Java program to rearrange characters in a string
// so that no two adjacent characters are same.
import
java.io.*;
import
java.util.*;
class
KeyComparator
implements
Comparator<Key> {
// Overriding compare()method of Comparator
public
int
compare(Key k1, Key k2)
{
if
(k1.freq < k2.freq)
return
1
;
else
if
(k1.freq > k2.freq)
return
-
1
;
return
0
;
}
}
class
Key {
int
freq;
// store frequency of character
char
ch;
Key(
int
val,
char
c)
{
freq = val;
ch = c;
}
}
class
GFG {
static
int
MAX_CHAR =
26
;
// Function to rearrange character of a string
// so that no char repeat twice
static
void
rearrangeString(String str)
{
int
n = str.length();
// Store frequencies of all characters in string
int
[] count =
new
int
[MAX_CHAR];
for
(
int
i =
0
; i < n; i++)
count[str.charAt(i) -
'a'
]++;
// Insert all characters with their frequencies
// into a priority_queue
PriorityQueue<Key> pq =
new
PriorityQueue<>(
new
KeyComparator());
for
(
char
c =
'a'
; c <=
'z'
; c++) {
int
val = c -
'a'
;
if
(count[val] >
0
)
pq.add(
new
Key(count[val], c));
}
// 'str' that will store resultant value
str =
""
;
// work as the previous visited element
// initial previous element be. ( '#' and
// it's frequency '-1' )
Key prev =
new
Key(-
1
,
'#'
);
// traverse queue
while
(pq.size() !=
0
) {
// pop top element from queue and add it
// to string.
Key k = pq.peek();
pq.poll();
str = str + k.ch;
// If frequency of previous character is less
// than zero that means it is useless, we
// need not to push it
if
(prev.freq >
0
)
pq.add(prev);
// make current character as the previous 'char'
// decrease frequency by 'one'
(k.freq)--;
prev = k;
}
// If length of the resultant string and original
// string is not same then string is not valid
if
(n != str.length())
System.out.println(
" Not valid String "
);
else
System.out.println(str);
}
// Driver program to test above function
public
static
void
main(String args[])
{
String str =
"bbbaa"
;
rearrangeString(str);
}
}
// This code is contributed by rachana soma
|
n
|
508.java
| 0.5
|
// Java program to print a string with
// no adjacent duplicates by doing
// minimum changes to original string
import
java.util.*;
import
java.lang.*;
public
class
GfG{
// Function to print simple string
public
static
String noAdjacentDup(String s1)
{
int
n = s1.length();
char
[] s = s1.toCharArray();
for
(
int
i =
1
; i < n; i++)
{
// If any two adjacent
// characters are equal
if
(s[i] == s[i -
1
])
{
// Initialize it to 'a'
s[i] =
'a'
;
// Traverse the loop until it
// is different from the left
// and right letter.
while
(s[i] == s[i -
1
] ||
(i +
1
< n && s[i] == s[i +
1
]))
s[i]++;
i++;
}
}
return
(
new
String(s));
}
// Driver function
public
static
void
main(String argc[]){
String s =
"geeksforgeeks"
;
System.out.println(noAdjacentDup(s));
}
}
/* This code is contributed by Sagar Shukla */
|
n
|
509.java
| 0.5
|
// Recursive Java program to search x in array
class
Test
{
static
int
arr[] = {
12
,
34
,
54
,
2
,
3
};
/* Recursive Method to search x in arr[l..r] */
static
int
recSearch(
int
arr[],
int
l,
int
r,
int
x)
{
if
(r < l)
return
-
1
;
if
(arr[l] == x)
return
l;
if
(arr[r] == x)
return
r;
return
recSearch(arr, l+
1
, r-
1
, x);
}
// Driver method
public
static
void
main(String[] args)
{
int
x =
3
;
//Method call to find x
int
index = recSearch(arr,
0
, arr.length-
1
, x);
if
(index != -
1
)
System.out.println(
"Element "
+ x +
" is present at index "
+
index);
else
System.out.println(
"Element "
+ x +
" is not present"
);
}
}
|
n
|
515.java
| 0.5
|
// Java program to find missing Number
class
Main {
// Function to ind missing number
static
int
getMissingNo(
int
a[],
int
n)
{
int
i, total;
total = (n +
1
) * (n +
2
) /
2
;
for
(i =
0
; i < n; i++)
total -= a[i];
return
total;
}
/* program to test above function */
public
static
void
main(String args[])
{
int
a[] = {
1
,
2
,
4
,
5
,
6
};
int
miss = getMissingNo(a,
5
);
System.out.println(miss);
}
}
|
n
|
517.java
| 0.5
|
// Java program to find smallest and second smallest elements
import
java.io.*;
class
SecondSmallest
{
/* Function to print first smallest and second smallest
elements */
static
void
print2Smallest(
int
arr[])
{
int
first, second, arr_size = arr.length;
/* There should be atleast two elements */
if
(arr_size <
2
)
{
System.out.println(
" Invalid Input "
);
return
;
}
first = second = Integer.MAX_VALUE;
for
(
int
i =
0
; i < arr_size ; i ++)
{
/* If current element is smaller than first
then update both first and second */
if
(arr[i] < first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and second
then update second */
else
if
(arr[i] < second && arr[i] != first)
second = arr[i];
}
if
(second == Integer.MAX_VALUE)
System.out.println(
"There is no second"
+
"smallest element"
);
else
System.out.println(
"The smallest element is "
+
first +
" and second Smallest"
+
" element is "
+ second);
}
/* Driver program to test above functions */
public
static
void
main (String[] args)
{
int
arr[] = {
12
,
13
,
1
,
10
,
34
,
1
};
print2Smallest(arr);
}
}
/*This code is contributed by Devesh Agrawal*/
|
n
|
524.java
| 0.5
|
class
Main
{
/* Function to get index of ceiling
of x in arr[low..high] */
static
int
ceilSearch(
int
arr[],
int
low,
int
high,
int
x)
{
int
i;
/* If x is smaller than or equal to first
element,then return the first element */
if
(x <= arr[low])
return
low;
/* Otherwise, linearly search for ceil value */
for
(i = low; i < high; i++)
{
if
(arr[i] == x)
return
i;
/* if x lies between arr[i] and arr[i+1]
including arr[i+1], then return arr[i+1] */
if
(arr[i] < x && arr[i+
1
] >= x)
return
i+
1
;
}
/* If we reach here then x is greater than the
last element of the array, return -1 in this case */
return
-
1
;
}
/* Driver program to check above functions */
public
static
void
main (String[] args)
{
int
arr[] = {
1
,
2
,
8
,
10
,
10
,
12
,
19
};
int
n = arr.length;
int
x =
3
;
int
index = ceilSearch(arr,
0
, n-
1
, x);
if
(index == -
1
)
System.out.println(
"Ceiling of "
+x+
" doesn't exist in array"
);
else
System.out.println(
"ceiling of "
+x+
" is "
+arr[index]);
}
}
|
n
|
526.java
| 0.5
|
// Java program to count occurrences
// of an element
class
Main
{
// Returns number of times x occurs in arr[0..n-1]
static
int
countOccurrences(
int
arr[],
int
n,
int
x)
{
int
res =
0
;
for
(
int
i=
0
; i<n; i++)
if
(x == arr[i])
res++;
return
res;
}
public
static
void
main(String args[])
{
int
arr[] = {
1
,
2
,
2
,
2
,
2
,
3
,
4
,
7
,
8
,
8
};
int
n = arr.length;
int
x =
2
;
System.out.println(countOccurrences(arr, n, x));
}
}
|
n
|
528.java
| 0.5
|
// Java program to Find the repeating
// and missing elements
import
java.io.*;
class
GFG {
static
void
printTwoElements(
int
arr[],
int
size)
{
int
i;
System.out.print(
"The repeating element is "
);
for
(i =
0
; i < size; i++) {
int
abs_val = Math.abs(arr[i]);
if
(arr[abs_val -
1
] >
0
)
arr[abs_val -
1
] = -arr[abs_val -
1
];
else
System.out.println(abs_val);
}
System.out.print(
"And the missing element is "
);
for
(i =
0
; i < size; i++) {
if
(arr[i] >
0
)
System.out.println(i +
1
);
}
}
// Driver code
public
static
void
main(String[] args)
{
int
arr[] = {
7
,
3
,
4
,
5
,
5
,
6
,
2
};
int
n = arr.length;
printTwoElements(arr, n);
}
}
// This code is contributed by Gitanjali
|
n
|
531.java
| 0.5
|
// Java program to Find the repeating
// and missing elements
import
java.io.*;
class
GFG {
static
int
x, y;
static
void
getTwoElements(
int
arr[],
int
n)
{
/* Will hold xor of all elements
and numbers from 1 to n */
int
xor1;
/* Will have only single set bit of xor1 */
int
set_bit_no;
int
i;
x =
0
;
y =
0
;
xor1 = arr[
0
];
/* Get the xor of all array elements */
for
(i =
1
; i < n; i++)
xor1 = xor1 ^ arr[i];
/* XOR the previous result with numbers from
1 to n*/
for
(i =
1
; i <= n; i++)
xor1 = xor1 ^ i;
/* Get the rightmost set bit in set_bit_no */
set_bit_no = xor1 & ~(xor1 -
1
);
/* Now divide elements into two sets by comparing
rightmost set bit of xor1 with the bit at the same
position in each element. Also, get XORs of two
sets. The two XORs are the output elements. The
following two for loops serve the purpose */
for
(i =
0
; i < n; i++) {
if
((arr[i] & set_bit_no) !=
0
)
/* arr[i] belongs to first set */
x = x ^ arr[i];
else
/* arr[i] belongs to second set*/
y = y ^ arr[i];
}
for
(i =
1
; i <= n; i++) {
if
((i & set_bit_no) !=
0
)
/* i belongs to first set */
x = x ^ i;
else
/* i belongs to second set*/
y = y ^ i;
}
/* *x and *y hold the desired output elements */
}
/* Driver program to test above function */
public
static
void
main(String[] args)
{
int
arr[] = {
1
,
3
,
4
,
5
,
1
,
6
,
2
};
int
n = arr.length;
getTwoElements(arr, n);
System.out.println(
" The missing element is "
+ x +
"and the "
+
"repeating number is "
+ y);
}
}
// This code is contributed by Gitanjali.
|
n
|
532.java
| 0.5
|
// Java program to check fixed point
// in an array using linear search
class
Main
{
static
int
linearSearch(
int
arr[],
int
n)
{
int
i;
for
(i =
0
; i < n; i++)
{
if
(arr[i] == i)
return
i;
}
/* If no fixed point present
then return -1 */
return
-
1
;
}
//main function
public
static
void
main(String args[])
{
int
arr[] = {-
10
, -
1
,
0
,
3
,
10
,
11
,
30
,
50
,
100
};
int
n = arr.length;
System.out.println(
"Fixed Point is "
+ linearSearch(arr, n));
}
}
|
n
|
533.java
| 0.5
|
// java program to find maximum
// element
class
Main
{
// function to find the
// maximum element
static
int
findMaximum(
int
arr[],
int
low,
int
high)
{
int
max = arr[low];
int
i;
for
(i = low; i <= high; i++)
{
if
(arr[i] > max)
max = arr[i];
}
return
max;
}
// main function
public
static
void
main (String[] args)
{
int
arr[] = {
1
,
30
,
40
,
50
,
60
,
70
,
23
,
20
};
int
n = arr.length;
System.out.println(
"The maximum element is "
+
findMaximum(arr,
0
, n-
1
));
}
}
|
n
|
535.java
| 0.5
|
// Java program to find a pair with the given difference
import
java.io.*;
class
PairDifference
{
// The function assumes that the array is sorted
static
boolean
findPair(
int
arr[],
int
n)
{
int
size = arr.length;
// Initialize positions of two elements
int
i =
0
, j =
1
;
// Search for a pair
while
(i < size && j < size)
{
if
(i != j && arr[j]-arr[i] == n)
{
System.out.print(
"Pair Found: "
+
"( "
+arr[i]+
", "
+ arr[j]+
" )"
);
return
true
;
}
else
if
(arr[j] - arr[i] < n)
j++;
else
i++;
}
System.out.print(
"No such pair"
);
return
false
;
}
// Driver program to test above function
public
static
void
main (String[] args)
{
int
arr[] = {
1
,
8
,
30
,
40
,
100
};
int
n =
60
;
findPair(arr,n);
}
}
/*This code is contributed by Devesh Agrawal*/
|
n
|
537.java
| 0.5
|
// JAVA Code for Find Second largest
// element in an array
class
GFG {
/* Function to print the second largest
elements */
public
static
void
print2largest(
int
arr[],
int
arr_size)
{
int
i, first, second;
/* There should be atleast two elements */
if
(arr_size <
2
)
{
System.out.print(
" Invalid Input "
);
return
;
}
first = second = Integer.MIN_VALUE;
for
(i =
0
; i < arr_size ; i++)
{
/* If current element is smaller than
first then update both first and second */
if
(arr[i] > first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and
second then update second */
else
if
(arr[i] > second && arr[i] != first)
second = arr[i];
}
if
(second == Integer.MIN_VALUE)
System.out.print(
"There is no second largest"
+
" element\n"
);
else
System.out.print(
"The second largest element"
+
" is "
+ second);
}
/* Driver program to test above function */
public
static
void
main(String[] args)
{
int
arr[] = {
12
,
35
,
1
,
10
,
34
,
1
};
int
n = arr.length;
print2largest(arr, n);
}
}
// This code is contributed by Arnav Kr. Mandal.
|
n
|
54.java
| 0.5
|
/* Java program to find first repeating element in arr[] */
import
java.util.*;
class
Main
{
// This function prints the first repeating element in arr[]
static
void
printFirstRepeating(
int
arr[])
{
// Initialize index of first repeating element
int
min = -
1
;
// Creates an empty hashset
HashSet<Integer> set =
new
HashSet<>();
// Traverse the input array from right to left
for
(
int
i=arr.length-
1
; i>=
0
; i--)
{
// If element is already in hash set, update min
if
(set.contains(arr[i]))
min = i;
else
// Else add element to hash set
set.add(arr[i]);
}
// Print the result
if
(min != -
1
)
System.out.println(
"The first repeating element is "
+ arr[min]);
else
System.out.println(
"There are no repeating elements"
);
}
// Driver method to test above method
public
static
void
main (String[] args)
throws
java.lang.Exception
{
int
arr[] = {
10
,
5
,
3
,
4
,
3
,
5
,
6
};
printFirstRepeating(arr);
}
}
|
n
|
541.java
| 0.5
|
// Java program to find common elements in three arrays
class
FindCommon
{
// This function prints common elements in ar1
void
findCommon(
int
ar1[],
int
ar2[],
int
ar3[])
{
// Initialize starting indexes for ar1[], ar2[] and ar3[]
int
i =
0
, j =
0
, k =
0
;
// Iterate through three arrays while all arrays have elements
while
(i < ar1.length && j < ar2.length && k < ar3.length)
{
// If x = y and y = z, print any of them and move ahead
// in all arrays
if
(ar1[i] == ar2[j] && ar2[j] == ar3[k])
{ System.out.print(ar1[i]+
" "
); i++; j++; k++; }
// x < y
else
if
(ar1[i] < ar2[j])
i++;
// y < z
else
if
(ar2[j] < ar3[k])
j++;
// We reach here when x > y and z < y, i.e., z is smallest
else
k++;
}
}
// Driver code to test above
public
static
void
main(String args[])
{
FindCommon ob =
new
FindCommon();
int
ar1[] = {
1
,
5
,
10
,
20
,
40
,
80
};
int
ar2[] = {
6
,
7
,
20
,
80
,
100
};
int
ar3[] = {
3
,
4
,
15
,
20
,
30
,
70
,
80
,
120
};
System.out.print(
"Common elements are "
);
ob.findCommon(ar1, ar2, ar3);
}
}
/*This code is contributed by Rajat Mishra */
|
n
|
542.java
| 0.5
|
// Java program to find pair with sum closest to x
import
java.io.*;
import
java.util.*;
import
java.lang.Math;
class
CloseSum {
// Prints the pair with sum cloest to x
static
void
printClosest(
int
arr[],
int
n,
int
x)
{
int
res_l=
0
, res_r=
0
;
// To store indexes of result pair
// Initialize left and right indexes and difference between
// pair sum and x
int
l =
0
, r = n-
1
, diff = Integer.MAX_VALUE;
// While there are elements between l and r
while
(r > l)
{
// Check if this pair is closer than the closest pair so far
if
(Math.abs(arr[l] + arr[r] - x) < diff)
{
res_l = l;
res_r = r;
diff = Math.abs(arr[l] + arr[r] - x);
}
// If this pair has more sum, move to smaller values.
if
(arr[l] + arr[r] > x)
r--;
else
// Move to larger values
l++;
}
System.out.println(
" The closest pair is "
+arr[res_l]+
" and "
+ arr[res_r]);
}
// Driver program to test above function
public
static
void
main(String[] args)
{
int
arr[] = {
10
,
22
,
28
,
29
,
30
,
40
}, x =
54
;
int
n = arr.length;
printClosest(arr, n, x);
}
}
/*This code is contributed by Devesh Agrawal*/
|
n
|
544.java
| 0.5
|
// Java program to find closest pair in an array
class
ClosestPair
{
// ar1[0..m-1] and ar2[0..n-1] are two given sorted
// arrays/ and x is given number. This function prints
// the pair from both arrays such that the sum of the
// pair is closest to x.
void
printClosest(
int
ar1[],
int
ar2[],
int
m,
int
n,
int
x)
{
// Initialize the diff between pair sum and x.
int
diff = Integer.MAX_VALUE;
// res_l and res_r are result indexes from ar1[] and ar2[]
// respectively
int
res_l =
0
, res_r =
0
;
// Start from left side of ar1[] and right side of ar2[]
int
l =
0
, r = n-
1
;
while
(l<m && r>=
0
)
{
// If this pair is closer to x than the previously
// found closest, then update res_l, res_r and diff
if
(Math.abs(ar1[l] + ar2[r] - x) < diff)
{
res_l = l;
res_r = r;
diff = Math.abs(ar1[l] + ar2[r] - x);
}
// If sum of this pair is more than x, move to smaller
// side
if
(ar1[l] + ar2[r] > x)
r--;
else
// move to the greater side
l++;
}
// Print the result
System.out.print(
"The closest pair is ["
+ ar1[res_l] +
", "
+ ar2[res_r] +
"]"
);
}
// Driver program to test above functions
public
static
void
main(String args[])
{
ClosestPair ob =
new
ClosestPair();
int
ar1[] = {
1
,
4
,
5
,
7
};
int
ar2[] = {
10
,
20
,
30
,
40
};
int
m = ar1.length;
int
n = ar2.length;
int
x =
38
;
ob.printClosest(ar1, ar2, m, n, x);
}
}
/*This code is contributed by Rajat Mishra */
|
n
|
545.java
| 0.5
|
// Java program to find a pair with a given
// sum in a sorted and rotated array
class
PairInSortedRotated
{
// This function returns true if arr[0..n-1]
// has a pair with sum equals to x.
static
boolean
pairInSortedRotated(
int
arr[],
int
n,
int
x)
{
// Find the pivot element
int
i;
for
(i =
0
; i < n -
1
; i++)
if
(arr[i] > arr[i+
1
])
break
;
int
l = (i +
1
) % n;
// l is now index of
// smallest element
int
r = i;
// r is now index of largest
//element
// Keep moving either l or r till they meet
while
(l != r)
{
// If we find a pair with sum x, we
// return true
if
(arr[l] + arr[r] == x)
return
true
;
// If current pair sum is less, move
// to the higher sum
if
(arr[l] + arr[r] < x)
l = (l +
1
) % n;
else
// Move to the lower sum side
r = (n + r -
1
) % n;
}
return
false
;
}
/* Driver program to test above function */
public
static
void
main (String[] args)
{
int
arr[] = {
11
,
15
,
6
,
8
,
9
,
10
};
int
sum =
16
;
int
n = arr.length;
if
(pairInSortedRotated(arr, n, sum))
System.out.print(
"Array has two elements"
+
" with sum 16"
);
else
System.out.print(
"Array doesn't have two"
+
" elements with sum 16 "
);
}
}
/*This code is contributed by Prakriti Gupta*/
|
n
|
547.java
| 0.5
|
// Java program to find largest pair sum in a given array
class
Test
{
static
int
arr[] =
new
int
[]{
12
,
34
,
10
,
6
,
40
};
/* Method to return largest pair sum. Assumes that
there are at-least two elements in arr[] */
static
int
findLargestSumPair()
{
// Initialize first and second largest element
int
first, second;
if
(arr[
0
] > arr[
1
])
{
first = arr[
0
];
second = arr[
1
];
}
else
{
first = arr[
1
];
second = arr[
0
];
}
// Traverse remaining array and find first and second largest
// elements in overall array
for
(
int
i =
2
; i<arr.length; i ++)
{
/* If current element is greater than first then update both
first and second */
if
(arr[i] > first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and second then update second */
else
if
(arr[i] > second && arr[i] != first)
second = arr[i];
}
return
(first + second);
}
// Driver method to test the above function
public
static
void
main(String[] args)
{
System.out.println(
"Max Pair Sum is "
+ findLargestSumPair());
}
}
|
n
|
549.java
| 0.5
|
// Java program to find smallest and second smallest elements
import
java.io.*;
class
SecondSmallest
{
/* Function to print first smallest and second smallest
elements */
static
void
print2Smallest(
int
arr[])
{
int
first, second, arr_size = arr.length;
/* There should be atleast two elements */
if
(arr_size <
2
)
{
System.out.println(
" Invalid Input "
);
return
;
}
first = second = Integer.MAX_VALUE;
for
(
int
i =
0
; i < arr_size ; i ++)
{
/* If current element is smaller than first
then update both first and second */
if
(arr[i] < first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and second
then update second */
else
if
(arr[i] < second && arr[i] != first)
second = arr[i];
}
if
(second == Integer.MAX_VALUE)
System.out.println(
"There is no second"
+
"smallest element"
);
else
System.out.println(
"The smallest element is "
+
first +
" and second Smallest"
+
" element is "
+ second);
}
/* Driver program to test above functions */
public
static
void
main (String[] args)
{
int
arr[] = {
12
,
13
,
1
,
10
,
34
,
1
};
print2Smallest(arr);
}
}
/*This code is contributed by Devesh Agrawal*/
|
n
|
55.java
| 0.5
|
import jdk.nashorn.internal.objects.NativeArray;
import javax.swing.JOptionPane ;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import java.sql.SQLSyntaxErrorException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Vector;
import static jdk.nashorn.internal.objects.NativeArray.sort;
import static jdk.nashorn.internal.runtime.ScriptObject.toPropertyDescriptor;
public class Dialog1 {
private static int n ;
private static String s ;
private static char[] a;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
n = input.nextInt() ;
s = input.next() ;
a = s.toCharArray();
for(int i = 0 ; i < 200 ; ++i) {
int cur = i ;
boolean fl = true ;
for(int j = 0 ; j < n ; ++j) {
if(a[j] == '+')
++cur ;
else
--cur ;
if(cur < 0)
fl = false ;
}
if(fl) {
System.out.print(cur);
return ;
}
}
}
}
|
n
|
551.java
| 0.5
|
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner s = new Scanner(System.in);
int n = Integer.parseInt(s.nextLine());
int ans = 0;
String inp = s.nextLine();
for(int i=0;i<n;i++) {
char k = inp.charAt(i);
if (k == '+')
ans++;
if (k == '-') {
if (ans>0)
ans--;
}
}
System.out.println(ans);
}
}
|
n
|
552.java
| 0.5
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//package newpackage;
import java.util.*;
/**
*
* @author parpaorsa
*/
public class NewClass {
static Scanner in=new Scanner(System.in);
public static void main(String[] args) {
int n = in.nextInt(),ans=Integer.MAX_VALUE,t=0;
String x = in.next();
for (int i = 0; i < n; i++) {
if(x.charAt(i)=='-')t--;
else t++;
ans=Math.min(ans,t);
}
if(ans <= 0)
System.out.println(Math.abs(ans)+t);
else
System.out.println(t);
}
}
|
n
|
553.java
| 0.5
|
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()) {
int n=sc.nextInt();
String s=sc.next();
int sum=0;
for(int i=0;i<s.length();i++) {
if(s.charAt(i)=='+') {
sum++;
}
if(s.charAt(i)=='-'&&sum!=0) {
sum--;
}
}
System.out.println(sum);
}
}
}
|
n
|
554.java
| 0.5
|
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner s = new Scanner(System.in);
int n = Integer.parseInt(s.nextLine());
int ans = Integer.MAX_VALUE;
int arr[] = new int[n];
for(int i=0;i<n;i++) {
arr[i] = s.nextInt();
}
for (int i=1;i<n;i++) {
ans = Math.min(ans, Math.min(arr[i],arr[0])/i);
}
for (int i=n-2;i>=0;i--){
ans = Math.min(ans, Math.min(arr[n-1],arr[i])/(n-i-1));
}
System.out.println(ans);
}
}
|
n
|
555.java
| 0.5
|
//package com.krakn.CF.B1159;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int min = 1000000000, temp;
for (int i = 0; i < n; i++) {
temp = arr[i] / Math.max(i, n - 1 - i);
if (temp < min)
min = temp;
// System.out.println(i + " " + temp);
}
System.out.println(min);
}
}
|
n
|
557.java
| 0.5
|
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int tmp;
int min=Integer.MAX_VALUE;
for(int i=0;i<n;i++) {
tmp=sc.nextInt();
if(i>n-1-i) {
tmp=tmp/i;
}else {
tmp=tmp/(n-1-i);
}
if(tmp<min) {
min=tmp;
}
}
System.out.println(min);
}
}
|
n
|
558.java
| 0.5
|
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner stdin = new Scanner(System.in);
/*int n = stdin.nextInt();
for(int i = 0; i < n; i++)
{
test(stdin);
}*/
test(stdin);
stdin.close();
}
public static void test(Scanner stdin)
{
int n = stdin.nextInt();
int min = Integer.MAX_VALUE;
for(int i = 0; i < n; i++)
{
int a = stdin.nextInt();
if((int)((1.0)*a/(Math.max(i, n - i - 1))) < min)
{ min = (int)((1.0)*a/(Math.max(i, n - i - 1))); }
}
System.out.println(min);
}
}
|
n
|
559.java
| 0.5
|
import java.io.*;
import java.util.*;
public class Main {
static Scanner in = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int n = in.nextInt();
int m = in.nextInt();
long boyMax = 0;
int NBoyMax = 0;
long sweets = 0;
TreeSet<Long> boyMember = new TreeSet<>();
for (int i = 0; i < n; i++) {
long input = in.nextLong();
boyMember.add(input);
if (boyMax < input) {
boyMax = input;
NBoyMax = 1;
} else if (boyMax == input) NBoyMax++;
sweets += (input * m);
}
long smallestGirl = (long) 1e8 + 1;
long sum = 0;
for (int i = 0; i < m; i++) {
long input = in.nextLong();
sum += input;
if (smallestGirl > input) smallestGirl = input;
}
if (smallestGirl < boyMember.last()) {
out.println(-1);
} else if (smallestGirl == boyMember.last()) {
sweets += sum - boyMember.last() * m;
out.println(sweets);
} else {
if (NBoyMax > 1) {
sweets += sum - boyMember.last() * m;
out.println(sweets);
} else {
Object[] boyList = boyMember.toArray();
if (boyList.length > 1) {
long boy = 0;
boy = (long)boyList[boyList.length - 2];
sweets += (sum - smallestGirl - boyMember.last() * (m - 1));
sweets += (smallestGirl - boy);
out.println(sweets);
} else {
out.println(-1);
}
}
}
in.close();
out.close();
}
}
|
n
|
563.java
| 0.5
|
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
if(n==k){
String s=new String();
for(int i=0;i<k;i++){
s=s+"1";
}
System.out.println(s);
}
else{
int a=(n-k)/2;
String s=new String();
for(int i=0;i<a && s.length()<n;i++){
s=s+"1";
}
if(s.length()<n){
s=s+"0";
}
while(s.length()<n){
s=s+s;
}
String s1=new String();
for(int i=0;i<n;i++){
s1=s1+Character.toString(s.charAt(i));
}
System.out.println(s1);
}
}
}
|
n
|
568.java
| 0.5
|
//package com.krakn.CF.D1159;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, k;
n = sc.nextInt();
k = sc.nextInt();
int a = (n - k) / 2;
StringBuilder s = new StringBuilder();
int i;
while (s.length() < n) {
i = 0;
while (i < a && s.length() < n) {
s.append("0");
i++;
}
if (s.length() < n) s.append("1");
}
System.out.println(s);
}
}
|
n
|
569.java
| 0.5
|
class
MaximumSum
{
/*Function to return max sum such that no two elements
are adjacent */
int
FindMaxSum(
int
arr[],
int
n)
{
int
incl = arr[
0
];
int
excl =
0
;
int
excl_new;
int
i;
for
(i =
1
; i < n; i++)
{
/* current max excluding i */
excl_new = (incl > excl) ? incl : excl;
/* current max including i */
incl = excl + arr[i];
excl = excl_new;
}
/* return max of incl and excl */
return
((incl > excl) ? incl : excl);
}
// Driver program to test above functions
public
static
void
main(String[] args)
{
MaximumSum sum =
new
MaximumSum();
int
arr[] =
new
int
[]{
5
,
5
,
10
,
100
,
10
,
5
};
System.out.println(sum.FindMaxSum(arr, arr.length));
}
}
// This code has been contributed by Mayank Jaiswal
|
n
|
57.java
| 0.5
|
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
if(n==k){
String s=new String();
for(int i=0;i<k;i++){
s=s+"1";
}
System.out.println(s);
}
else{
int a=(n-k)/2;
String s=new String();
while(s.length()<n){
for(int i=0;i<a && s.length()<n;i++){
s=s+"1";
}
if(s.length()<n){
s=s+"0";
}
}
System.out.println(s);
}
}
}
|
n
|
570.java
| 0.5
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class SFly {
public static void main(String[] args) throws IOException {
BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
int planet = Integer.parseInt(lector.readLine());
int ini = Integer.parseInt(lector.readLine());
double peso = ini;
int[] desp = new int[planet];
int[] ater = new int[planet];
String[] temp = lector.readLine().split(" ");
for(int i=0; i<planet; i++) {
desp[i] = Integer.parseInt(temp[i]);
if(desp[i] == 1) {
System.out.println(-1);
lector.close();
return;
}
}
temp = lector.readLine().split(" ");
for(int i=0; i<planet; i++) {
ater[i] = Integer.parseInt(temp[i]);
if(ater[i] == 1) {
System.out.println(-1);
lector.close();
return;
}
}
temp = null;
int i=planet-1;
peso = (peso*ater[0])/(ater[0]-1);
while(i>0) {
peso = (peso*desp[i])/(desp[i]-1);
peso = (peso*ater[i])/(ater[i]-1);
i--;
}
peso = (peso*desp[0])/(desp[0]-1);
peso = peso - ini;
System.out.println(peso);
lector.close();
}
}
|
n
|
571.java
| 0.5
|
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
/* spar5h */
public class cf1 implements Runnable{
public void run() {
InputReader s = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t = 1;
while(t-- > 0) {
int n = s.nextInt(), m = s.nextInt();
int[] a = new int[n + 1];
for(int i = 1; i <= n; i++)
a[i] = s.nextInt();
int[] b = new int[n + 1];
for(int i = 1; i <= n; i++)
b[i] = s.nextInt();
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(a[1]);
for(int i = 2; i <= n; i++) {
list.add(b[i]); list.add(a[i]);
}
list.add(b[1]);
double wt = m;
boolean check = true;
for(int i = list.size() - 1; i >= 0; i--) {
if(list.get(i) <= 1) {
check = false; break;
}
double x = wt / (list.get(i) - 1);
wt += x;
}
if(check)
w.println(wt - m);
else
w.println(-1);
}
w.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new cf1(),"cf1",1<<26).start();
}
}
|
n
|
574.java
| 0.5
|
import java.util.*;
public class helloWorld
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
String str = in.next();
boolean[] exist = new boolean[200];
int dn[][] = new int[200][m+1];
for(int i = 0; i < n; i++) {
int a = str.charAt(i);
exist[a] = true;
dn[a][1] = a - 'a' + 1;
}
for(int k = 2; k <= m; k++)
for(int i = 'a'; i <= 'z'; i++)
if(exist[i]) {
int a = 0;
for(int j = i+2; j <= 'z'; j++)
if(dn[j][k-1] > 0 && (a == 0 || (a > dn[j][k-1]) ) )
a = dn[j][k-1];
if(a > 0)
dn[i][k] = a + i - 'a' + 1;
}
int ans = -1;
for(int i = 'a'; i <= 'z'; i++)
if(dn[i][m] > 0 && (ans == -1 || ans > dn[i][m]) )
ans = dn[i][m];
System.out.println(ans);
in.close();
}
}
|
n
|
578.java
| 0.5
|
import java.io.*;
public class First {
StreamTokenizer in;
PrintWriter out;
int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}
long nextLong() throws IOException {
in.nextToken();
return (long) in.nval;
}
String nextString() throws IOException {
in.nextToken();
return in.sval;
}
void run() throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
solve();
out.flush();
}
void solve() throws IOException {
int n = nextInt(), k = nextInt(), sum = 0, count = 0;
String str = nextString();
char[] arr = str.toCharArray();
boolean[] bool = new boolean[26];
for(char ch: arr){
bool[((int)ch)-97] = true;
}
for(int i = 0; i < 26; i++){
if(bool[i]){
sum += i+1;
count++;
i += 1;
}
if(count == k) break;
}
if(count == k) out.println(sum);
else out.println(-1);
}
public static void main(String[] args) throws IOException {
new First().run();
}
}
|
n
|
580.java
| 0.5
|
import java.util.*;
import java.io.*;
public class Solution
{
public static void main(String [] args) throws IOException
{
PrintWriter pw=new PrintWriter(System.out);//use pw.println() not pw.write();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(br.readLine());
/*
inputCopy
5 3
xyabd
outputCopy
29
inputCopy
7 4
problem
outputCopy
34
inputCopy
2 2
ab
outputCopy
-1
inputCopy
12 1
abaabbaaabbb
outputCopy
1
*/
int n=Integer.parseInt(st.nextToken());
int k=Integer.parseInt(st.nextToken());
st=new StringTokenizer(br.readLine());
String str=st.nextToken();
char [] arr=str.toCharArray();
Arrays.sort(arr);
int weight=arr[0]-96;
char a=arr[0];
int included=1;
for(int i=1;i<arr.length;++i)
{
if(included==k)
break;
char c=arr[i];
if(c-a<2)
continue;
weight+=arr[i]-96;
++included;
a=arr[i];
}
if(included==k)
pw.println(weight);
else
pw.println(-1);
pw.close();//Do not forget to write it after every program return statement !!
}
}
/*
→Judgement Protocol
Test: #1, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
5 3
xyabd
Output
29
Answer
29
Checker Log
ok 1 number(s): "29"
Test: #2, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
7 4
problem
Output
34
Answer
34
Checker Log
ok 1 number(s): "34"
Test: #3, time: 139 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
2 2
ab
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #4, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
12 1
abaabbaaabbb
Output
1
Answer
1
Checker Log
ok 1 number(s): "1"
Test: #5, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 13
qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa
Output
169
Answer
169
Checker Log
ok 1 number(s): "169"
Test: #6, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 14
qwertyuiopasdfghjklzxcvbnmaaaaaaaaaaaaaaaaaaaaaaaa
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #7, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
1 1
a
Output
1
Answer
1
Checker Log
ok 1 number(s): "1"
Test: #8, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 1
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Output
1
Answer
1
Checker Log
ok 1 number(s): "1"
Test: #9, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 2
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #10, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
13 13
uwgmkyqeiaocs
Output
169
Answer
169
Checker Log
ok 1 number(s): "169"
Test: #11, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
13 13
hzdxpbfvrltnj
Output
182
Answer
182
Checker Log
ok 1 number(s): "182"
Test: #12, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
1 1
n
Output
14
Answer
14
Checker Log
ok 1 number(s): "14"
Test: #13, time: 92 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
10 8
smzeblyjqw
Output
113
Answer
113
Checker Log
ok 1 number(s): "113"
Test: #14, time: 78 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
20 20
tzmvhskkyugkuuxpvtbh
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #15, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
30 15
wjzolzzkfulwgioksfxmcxmnnjtoav
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #16, time: 93 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
40 30
xumfrflllrrgswehqtsskefixhcxjrxbjmrpsshv
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #17, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
50 31
ahbyyoxltryqdmvenemaqnbakglgqolxnaifnqtoclnnqiabpz
Output
-1
Answer
-1
Checker Log
ok 1 number(s): "-1"
Test: #18, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
10 7
iuiukrxcml
Output
99
Answer
99
Checker Log
ok 1 number(s): "99"
Test: #19, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
38 2
vjzarfykmrsrvwbwfwldsulhxtykmjbnwmdufa
Output
5
Answer
5
Checker Log
ok 1 number(s): "5"
Test: #20, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
12 6
fwseyrarkwcd
Output
61
Answer
61
Checker Log
ok 1 number(s): "61"
Test: #21, time: 109 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
2 2
ac
Output
4
Answer
4
Checker Log
ok 1 number(s): "4"
Test: #22, time: 108 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
1 1
c
Output
3
Answer
3
Checker Log
ok 1 number(s): "3"
Test: #23, time: 124 ms., memory: 0 KB, exit code: 0, checker exit code: 0, verdict: OK
Input
2 2
ad
Output
5
Answer
5
Checker Log
ok 1 number(s): "5"
Test: #24, time: 77 ms., memory: 0 KB, exit code: 0, checker exit code: 1, verdict: WRONG_ANSWER
Input
2 1
ac
Output
-1
Answer
1
Checker Log
wrong answer 1st number
*/
|
n
|
582.java
| 0.5
|
import java.util.*;
public class helloWorld
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int cnt = 0;
String ans = "Yes";
for(int i = 0; i < n; i++)
cnt += in.nextInt();
for(int i = 0; i < n; i++)
cnt -= in.nextInt();
if(cnt < 0)
ans = "No";
System.out.println(ans);
in.close();
}
}
|
n
|
588.java
| 0.5
|
import java.util.*;
import java.io.*;
public class Piles {
static int summation(int arr[]) {
int k, sum=0;
for(k=0;k<arr.length;k++) {
sum = sum + arr[k];
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n>=1 && n<=50) {
int x[] = new int[n];
int y[] = new int[n];
for(int i=0;i<n;i++) {
x[i] = sc.nextInt();
}
for(int j=0;j<n;j++) {
y[j] = sc.nextInt();
}
int xsum = summation(x);
int ysum = summation(y);
if(xsum>=ysum) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
}
|
n
|
589.java
| 0.5
|
// JAVA Code to find total count of an element
// in a range
class
GFG {
// Returns count of element in arr[left-1..right-1]
public
static
int
findFrequency(
int
arr[],
int
n,
int
left,
int
right,
int
element)
{
int
count =
0
;
for
(
int
i = left -
1
; i < right; ++i)
if
(arr[i] == element)
++count;
return
count;
}
/* Driver program to test above function */
public
static
void
main(String[] args)
{
int
arr[] = {
2
,
8
,
6
,
9
,
8
,
6
,
8
,
2
,
11
};
int
n = arr.length;
// Print frequency of 2 from position 1 to 6
System.out.println(
"Frequency of 2 from 1 to 6 = "
+
findFrequency(arr, n,
1
,
6
,
2
));
// Print frequency of 8 from position 4 to 9
System.out.println(
"Frequency of 8 from 4 to 9 = "
+
findFrequency(arr, n,
4
,
9
,
8
));
}
}
// This code is contributed by Arnav Kr. Mandal.
|
n
|
59.java
| 0.5
|
import java.util.Scanner;
public class Stones {
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
int n=input.nextInt();
int s1=0;
int s2=0;
for (int i=0;i<n;++i)
s1+=input.nextInt();
for (int i=0;i<n;++i)
s2+=input.nextInt();
if (s1 >= s2)
System.out.println("Yes");
else
System.out.println("No");
}
}
|
n
|
590.java
| 0.5
|
import java.util.Scanner;
public class Piles {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] a = new int[2]; int x = scan.nextInt();
for(int i = 0; i < 2; i++) for(int j = 0; j < x; j++) a[i] += scan.nextInt();
System.out.println(a[1] <= a[0] ? "Yes" : "No");
}
}
|
n
|
591.java
| 0.5
|
import java.util.*;
import static java.lang.Math.*;
import java.io.*;
public class SolutionB {
public static void main(String args[])throws IOException{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
int a[] = new int[n];
for(int i = 0; i < n; i++){
a[i] = sc.nextInt();
if(!set1.contains(a[i])){
set1.add(a[i]);
}else{
System.out.println(0);
return;
}
}
for(int i = 0; i < n; i++){
int b = a[i] & k;
if(b != a[i] && set1.contains(b)){
System.out.println(1);
return;
}
//if(!set2.contains(b)){
//set2.add(b);
//}else{
// System.out.println(2);
// return;
//}
}
for(int i = 0; i < n; i++){
int b = a[i] & k;
if(b != a[i] && set2.contains(b)){
System.out.println(2);
return;
}else{
set2.add(b);
}
}
System.out.println(-1);
}
}
|
n
|
593.java
| 0.5
|
//package contese_476;
import java.util.*;
public class q1
{
int m=(int)1e9+7;
public class Node
{
int a;
int b;
public void Node(int a,int b)
{
this.a=a;
this.b=b;
}
}
public int mul(int a ,int b)
{
a=a%m;
b=b%m;
return((a*b)%m);
}
public int pow(int a,int b)
{
int x=1;
while(b>0)
{
if(b%2!=0)
x=mul(x,a);
a=mul(a,a);
b=b/2;
}
return x;
}
public static long gcd(long a,long b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
HashMap<Integer,Integer> h=new HashMap();
//HashMap<Integer,Integer> h1=new HashMap();
int[] a=new int[n];
int x=sc.nextInt();
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
if(h.get(a[i])==null)
{
h.put(a[i], 1);
//h1.put(a[i],i);
}
else
{
System.out.print(0);
System.exit(0);
}
}
for(int i=0;i<n;i++)
{
int num=a[i]&x;
if(num==a[i])
continue;
if(h.get(num)==null)
continue;
else
{
System.out.print(1);
System.exit(0);
}
}
for(int i=0;i<n;i++)
{
int num=a[i]&x;
if(num==a[i])
continue;
if(h.get(num)==null)
h.put(num, 1);
else
{
System.out.print(2);
System.exit(0);
}
}
System.out.print(-1);
}
}
|
n
|
594.java
| 0.5
|
/**
* Created by Baelish on 7/30/2018.
*/
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class B {
public static void main(String[] args)throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int ans = -1;
int f[] = new int[(int)2e5+50];
int g[] = new int[(int)2e5+50];
int n = in.nextInt(), x = in.nextInt();
int arr[] = new int[n+1];
for (int i = 1; i <= n && ans == -1; i++) {
int a = in.nextInt();
if(f[a] > 0){
ans = 0; break;
}
f[a]++;
arr[i] = a;
}
for (int i = 1; i <= n && ans == -1; i++) {
int a = arr[i] & x;
if( (a == arr[i] && f[a] > 1) || (a != arr[i] && f[a] > 0)){
ans = 1; break;
}
g[a]++;
}
for (int i = 1; i <= n && ans == -1; i++) {
int a = arr[i] & x;
if(g[a] > 1){
ans = 2; break;
}
//g[a]++;
}
pw.println(ans);
pw.close();
}
static void debug(Object...obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
static final int ints[] = new int[128];
public FastReader(InputStream is){
for(int i='0';i<='9';i++) ints[i]=i-'0';
this.is = is;
}
public int readByte(){
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while((b = readByte()) != -1 && isSpaceChar(b));
return b;
}
public String next(){
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt(){
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = (num<<3) + (num<<1) + ints[b];
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = (num<<3) + (num<<1) + ints[b];
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
/* public char nextChar() {
return (char)skip();
}*/
public char[] next(int n){
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
/*private char buff[] = new char[1005];
public char[] nextCharArray(){
int b = skip(), p = 0;
while(!(isSpaceChar(b))){
buff[p++] = (char)b;
b = readByte();
}
return Arrays.copyOf(buff, p);
}*/
}
}
|
n
|
599.java
| 0.5
|
// Java program to find max value of i*arr[i]
import
java.util.Arrays;
class
Test
{
static
int
arr[] =
new
int
[]{
10
,
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
};
// Returns max possible value of i*arr[i]
static
int
maxSum()
{
// Find array sum and i*arr[i] with no rotation
int
arrSum =
0
;
// Stores sum of arr[i]
int
currVal =
0
;
// Stores sum of i*arr[i]
for
(
int
i=
0
; i<arr.length; i++)
{
arrSum = arrSum + arr[i];
currVal = currVal+(i*arr[i]);
}
// Initialize result as 0 rotation sum
int
maxVal = currVal;
// Try all rotations one by one and find
// the maximum rotation sum.
for
(
int
j=
1
; j<arr.length; j++)
{
currVal = currVal + arrSum-arr.length*arr[arr.length-j];
if
(currVal > maxVal)
maxVal = currVal;
}
// Return result
return
maxVal;
}
// Driver method to test the above function
public
static
void
main(String[] args)
{
System.out.println(
"Max sum is "
+ maxSum());
}
}
|
n
|
6.java
| 0.5
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class TaskA {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
long i = sc.nextInt();
long goal = sc.nextLong();
// long goal=sum;
if(i>goal) {
i=goal;
}
int count = 0;
while (goal >= 0) {
if (goal - i >= 0) {
goal = goal - i;
count++;
} else
i--;
if (goal == 0)
break;
}
out.print(count);
out.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
|
n
|
603.java
| 0.5
|
import java.util.*;
public class CoinsTask {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int S = in.nextInt();
int mCoins = 0;
while(S/n != 0) {
mCoins+=1;
S-=n;
}
mCoins = S == 0? mCoins : mCoins+1;
System.out.print(mCoins);
}
}
|
n
|
604.java
| 0.5
|
import java.util.Scanner;
public class P1075A
{
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
long n,x,y;
n=scan.nextLong();
x=scan.nextLong();
y=scan.nextLong();
boolean flag=true,flag1=false,flag2=false;
long w1,w2,b1,b2;
long W=0l,B=0l;
w1=w2=1; b1=b2=n;
while(w1<n)
{
if(w1==x)
{flag1=true; break;}
if(w2==y)
break;
++w1; ++w2; ++W;
}
if(flag1)
W+=(y-w2);
else
W+=(x-w1);
while(b1>1)
{
if(b1==x)
{flag2=true; break;}
if(b2==y)
break;
--b1; --b2; ++B;
}
if(flag2)
B+=(b2-y);
else
B+=(b1-x);
if(B<W)
System.out.println("Black");
else
System.out.println("White");
}
}
|
n
|
617.java
| 0.5
|
import java.util.*;
public class kingrace {public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
long a = input.nextLong();
input.nextLine();
String [] coo = input.nextLine().split(" ");
long xcoin = Long.parseLong(coo[0]);
long ycoin = Long.parseLong(coo[1]);
coordinates first = new coordinates(1,1,a);
coordinates second = new coordinates(a,a,a);
double x = (double)Math.sqrt(Math.abs((xcoin-1)*(xcoin-1)+(ycoin-1)*(ycoin-1)));
double y = (double)Math.sqrt(Math.abs((xcoin-a)*(xcoin-a)+(ycoin-a)*(ycoin-a)));
long c = 0;
long d = 0;
if (x>y)
{
System.out.println("Black");
}
else if(x<y)
{
System.out.println("White");
}
else {
c = first.Distance(new coordinates(xcoin,ycoin,a));
d = second.Distance(new coordinates(xcoin,ycoin,a));
}
if(d!=0&&c!=0)
if (d<c)
{
System.out.println("Black");
}
else
{
System.out.println("White");
}
//System.out.prlongln(c +" "+d);
input.close();
}
}
class coordinates{
private long xcoord;
private long ycoord;
private long dim;
public coordinates(long x, long y, long dimensions)
{
xcoord = x;
ycoord = y;
dim = dimensions;
}
public void setCoordinates(long x, long y)
{
xcoord = x;
ycoord = y;
}
public long Distance(coordinates num)
{
long distance = 0;
while ((this.xcoord!=num.xcoord||this.ycoord!=num.ycoord))
{
if (num.xcoord-this.xcoord==1 &&num.ycoord==this.ycoord)
{
distance ++; this.setCoordinates(this.xcoord+1, this.ycoord);
}
else if (num.xcoord-this.xcoord==-1 &&num.ycoord==this.ycoord)
{
distance ++; this.setCoordinates(this.xcoord-1, this.ycoord);
}
else if (num.xcoord-this.xcoord==0 &&num.ycoord-this.ycoord==1)
{distance ++; this.setCoordinates(this.xcoord, this.ycoord+1);}
else if (num.xcoord-this.xcoord==0 &&num.ycoord-this.ycoord==-1) {
distance ++; this.setCoordinates(this.xcoord, this.ycoord-1);
}
else if (num.xcoord-this.xcoord>=0 &&num.ycoord-this.ycoord<=0)
{
distance ++; this.setCoordinates(this.xcoord+1, this.ycoord-1);
}
else if (num.xcoord-this.xcoord>=0 &&num.ycoord-this.ycoord>=0)
{
distance ++; this.setCoordinates(this.xcoord+1, this.ycoord+1);
}
else if (num.xcoord-this.xcoord<=0 &&num.ycoord-this.ycoord<=0)
{
distance ++; this.setCoordinates(this.xcoord-1, this.ycoord-1);
}
else if (num.xcoord-this.xcoord<=0 &&num.ycoord-this.ycoord>=0)
{distance ++; this.setCoordinates(this.xcoord-1, this.ycoord+1);
}
}
return distance;
}
}
|
n
|
618.java
| 0.5
|
// Java program to count the number of
// indexes in range L R such that
// Ai = Ai+1
class
GFG {
// function that answers every query
// in O(r-l)
static
int
answer_query(
int
a[],
int
n,
int
l,
int
r)
{
// traverse from l to r and count
// the required indexes
int
count =
0
;
for
(
int
i = l; i < r; i++)
if
(a[i] == a[i +
1
])
count +=
1
;
return
count;
}
// Driver Code
public
static
void
main(String[] args)
{
int
a[] = {
1
,
2
,
2
,
2
,
3
,
3
,
4
,
4
,
4
};
int
n = a.length;
// 1-st query
int
L, R;
L =
1
;
R =
8
;
System.out.println(
answer_query(a, n, L, R));
// 2nd query
L =
0
;
R =
4
;
System.out.println(
answer_query(a, n, L, R));
}
}
// This code is contribute by
// Smitha Dinesh Semwal
|
n
|
62.java
| 0.5
|
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt(),m=sc.nextInt();
int loca[]=new int[n+m];
int res[]=new int[m];
for(int i=0;i<n+m;i++)
loca[i]=sc.nextInt();
int y=0;
int driver[]=new int[m];
for(int i=0;i<n+m;i++){
int x=sc.nextInt();
if(x==1)
driver[y++]=i;
}
int i=0,j=0,p=0,q=0;
for(i=0;i<m+n;i++) {
if(i==driver[0])
{i++;break;}
if(loca[i]<loca[driver[0]])
res[0]++;
else
break;
}
//j=1;
for(;i<n+m;i++){
int coor=loca[i];
/*if(coor>q&&j!=0)
j++;*/
if(j==m-1)
break;
p=driver[j];q=driver[j+1];
if(i==j)
continue;
int d1=coor-loca[p],d2=loca[q]-coor;
if(d2==0)
{j++;continue;}
if(d1<=d2)
res[j]++;
else
res[j+1]++;
//add check for j+1<m
//handle cases for j==0 && j==m-1
}
for(;i<m+n;i++) {
if(i==driver[j])
{i++;break;}
if(loca[i]>loca[driver[j]])
res[j]++;
else
break;
}
for(i=0;i<m;i++)
System.out.print(res[i]+" ");
}
}
|
n
|
621.java
| 0.5
|
import java.util.Scanner;
public class TaxiDriversAndLyft2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long n = scanner.nextLong();
long m = scanner.nextLong();
long[] people = new long[(int) (n+m)];
int[] taxiDrivers = new int[(int) (n+m)];
for(int i = 0;i< (n+m); i++) {
people[i] = scanner.nextLong();
}
for(int i = 0;i< (n+m); i++) {
taxiDrivers[i] = scanner.nextInt();
}
int lastTaxiDriverIndex = -1;
long[] riderCountArray = new long[(int) (m)];
long[] a1 = new long[(int)n];
long[] b1 = new long[(int)m];
int j=0, k=0;
for(int i = 0;i< (n+m); i++) {
if(taxiDrivers[i] == 0) {
a1[j] = people[i];
j++;
}
else {
b1[k] = people[i];
k++;
}
}
int l = 0, q=0;
for(int i=0;i<j;i++) {
while ((l<m-1 && m>1) && Math.abs(a1[i] - b1[l]) > Math.abs(a1[i] - b1[l+1])) {
l++;
}
riderCountArray[l]++;
}
for(int i = 0;i< (m); i++) {
System.out.print(riderCountArray[i]+" ");
}
}
}
|
n
|
622.java
| 0.5
|
import java.util.*;
import java.io.*;
public class Solution{
public static long page(long p,long k){
return (p-1)/k;
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
int m = sc.nextInt();
long k = sc.nextLong();
long[] p = new long[m];
long del = 0;
long nb = 1;
int op = 0;
for(int i=0;i<m;i++) p[i] = sc.nextLong();
for(int i=1;i<m;i++){
if(page(p[i]-del,k)!=page(p[i-1]-del,k)){
del += nb;
nb = 1;
op++;
}else{
nb++;
}
}
if(nb!=0) op++;
System.out.println(op);
}
}
|
n
|
632.java
| 0.5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.