content
stringlengths 219
31.2k
| complexity
stringclasses 5
values | file_name
stringlengths 6
9
| complexity_ranked
float64 0.1
0.9
|
---|---|---|---|
import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static long oo = 1000000000000L;
static int[][] memo;
public static void main(String[] args) throws IOException {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
if(n % 2 == 0) {
for(int i = 0; i < n; ++i) {
if(a[i] >= 0)
a[i] = -a[i] - 1;
}
}
else {
int maxi = -1, max = -1;
for(int i = 0; i < n; ++i) {
int x = a[i] >= 0 ? -a[i] - 1 : a[i];
x = -x;
if(x > max) {
max = x; maxi = i;
}
}
if(max == 1) {
a[0] = 0;
}
else {
for(int i = 0; i < n; ++i) {
if(i == maxi) {
if(a[i] < 0)
a[i] = -a[i] - 1;
}
else {
if(a[i] >= 0)
a[i] = -a[i] - 1;
}
}
}
}
for(int x : a)
System.out.print(x + " ");
out.close();
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static boolean nextPermutation(int[] a) {
for(int i = a.length - 2; i >= 0; --i) {
if(a[i] < a[i+1]) {
for(int j = a.length - 1; ; --j) {
if(a[i] < a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
for(i++, j = a.length - 1; i < j; ++i, --j) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
return true;
}
}
}
}
return false;
}
static void shuffle(int[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
int t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(long[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
long t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static int lower_bound(int[] a, int n, int k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
super();
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return this.first != o.first ? this.first - o.first : this.second - o.second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
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 {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
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 String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
|
n
|
1003.java
| 0.5 |
import java.util.Scanner;
public class NickAndArray {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int array[]=new int[n];
int max=Integer.MAX_VALUE;
int index=0;
for(int i=0;i<n;i++)
{
int k=sc.nextInt();
array[i]=k;
if(array[i]>=0)
{
array[i]=-array[i]-1;
}
if(array[i]<max)
{
max=array[i];
index=i;
}
}
if(n%2!=0)
{
array[index]=-array[index]-1;
}
for(int i=0;i<n;i++)
{
System.out.print(array[i]+" " );
}
}
}
|
n
|
1004.java
| 0.5 |
import java.util.*;
public class Main {
static int n=5;
static int[] arr=new int[5];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for (int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
for (int i=0;i<n;i++)
{
if (arr[i]>=0)
{
arr[i]=-arr[i]-1;
}
}
if (n%2!=0)
{
int min=0;
for (int i=1;i<n;i++)
{
if (arr[i]<arr[min])
min=i;
}
arr[min]=-arr[min]-1;
}
for (int x:arr)
{
System.out.print(x + " ");
}
}
}
|
n
|
1005.java
| 0.5 |
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int [] a= new int[n];
int k=0;
int m=0;
for (int i=0;i<n;i++){
a[i]=sc.nextInt();
if (a[i]>=0){
a[i]=-a[i]-1;
}
if (a[i]<m){
m=a[i];
k=i;
}
}
if (n%2==1){
a[k]=-a[k]-1;
}
for (int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
}
}
|
n
|
1006.java
| 0.5 |
import java.util.*;
import java.io.*;
import java.math.*;
public class round569d2c {
public static void main(String args[]) {
FastScanner in = new FastScanner(System.in);
int n = in.nextInt();
int q = in.nextInt();
ArrayDeque<Integer> deq = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
deq.addLast(in.nextInt());
}
long[] queries = new long[q];
for (int i = 0; i < q; i++) {
queries[i] = in.nextLong();
}
int[] origAs = new int[n-1];
int[] origBs = new int[n-1];
for (int i = 0; i < n-1; i++) {
int a = deq.pollFirst();
int b = deq.pollFirst();
origAs[i] = a;
origBs[i] = b;
if (a > b) {
deq.addFirst(a);
deq.addLast(b);
}
else {
deq.addFirst(b);
deq.addLast(a);
}
}
int[] repeatAs = new int[n-1];
int[] repeatBs = new int[n-1];
for (int i = 0; i < n-1; i++) {
int a = deq.pollFirst();
int b = deq.pollFirst();
repeatAs[i] = a;
repeatBs[i] = b;
if (a > b) {
deq.addFirst(a);
deq.addLast(b);
}
else {
deq.addFirst(b);
deq.addLast(a);
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < q; i++) {
long query = queries[i] - 1;
if (query < n-1) {
sb.append(origAs[(int)query] + " " + origBs[(int)query] + "\n");
}
else {
query %= (n-1);
sb.append(repeatAs[(int)query] + " " + repeatBs[(int)query] + "\n");
}
}
System.out.println(sb);
}
// ======================================================================================
// =============================== Reference Code =======================================
// ======================================================================================
static int greatestDivisor(int n) {
int limit = (int) Math.sqrt(n);
int max = 1;
for (int i = 2; i <= limit; i++) {
if (n % i == 0) {
max = Integer.max(max, i);
max = Integer.max(max, n / i);
}
}
return max;
}
// Method to return all primes smaller than or equal to
// n using Sieve of Eratosthenes
static boolean[] sieveOfEratosthenes(int n) {
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a prime
if (prime[p] == true) {
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
// Binary search for number greater than or equal to target
// returns -1 if number not found
private static int bin_gteq(int[] a, int key) {
int low = 0;
int high = a.length;
int max_limit = high;
while (low < high) {
int mid = low + (high - low) / 2;
if (a[mid] < key) {
low = mid + 1;
} else
high = mid;
}
return high == max_limit ? -1 : high;
}
public static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static class Tuple<X, Y> {
public final X x;
public final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
public String toString() {
return "(" + x + "," + y + ")";
}
}
static class Tuple3<X, Y, Z> {
public final X x;
public final Y y;
public final Z z;
public Tuple3(X x, Y y, Z z) {
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return "(" + x + "," + y + "," + z + ")";
}
}
static Tuple3<Integer, Integer, Integer> gcdExtended(int a, int b, int x, int y) {
// Base Case
if (a == 0) {
x = 0;
y = 1;
return new Tuple3(0, 1, b);
}
int x1 = 1, y1 = 1; // To store results of recursive call
Tuple3<Integer, Integer, Integer> tuple = gcdExtended(b % a, a, x1, y1);
int gcd = tuple.z;
x1 = tuple.x;
y1 = tuple.y;
// Update x and y using results of recursive
// call
x = y1 - (b / a) * x1;
y = x1;
return new Tuple3(x, y, gcd);
}
// Returns modulo inverse of a
// with respect to m using extended
// Euclid Algorithm. Refer below post for details:
// https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
static int inv(int a, int m) {
int m0 = m, t, q;
int x0 = 0, x1 = 1;
if (m == 1)
return 0;
// Apply extended Euclid Algorithm
while (a > 1) {
// q is quotient
q = a / m;
t = m;
// m is remainder now, process
// same as euclid's algo
m = a % m;
a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
// Make x1 positive
if (x1 < 0)
x1 += m0;
return x1;
}
// k is size of num[] and rem[].
// Returns the smallest number
// x such that:
// x % num[0] = rem[0],
// x % num[1] = rem[1],
// ..................
// x % num[k-2] = rem[k-1]
// Assumption: Numbers in num[] are pairwise
// coprime (gcd for every pair is 1)
static int findMinX(int num[], int rem[], int k) {
// Compute product of all numbers
int prod = 1;
for (int i = 0; i < k; i++)
prod *= num[i];
// Initialize result
int result = 0;
// Apply above formula
for (int i = 0; i < k; i++) {
int pp = prod / num[i];
result += rem[i] * inv(pp, num[i]) * pp;
}
return result % prod;
}
/**
* Source: Matt Fontaine
*/
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int chars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (chars == -1)
throw new InputMismatchException();
if (curChar >= chars) {
curChar = 0;
try {
chars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (chars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String next() {
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 String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
|
n
|
1007.java
| 0.5 |
import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static long oo = 1000000000000L;
public static void main(String[] args) throws IOException {
int n = in.nextInt();
int q = in.nextInt();
ArrayDeque<Integer> dq = new ArrayDeque<>();
int max = -1;
for(int i = 0; i < n; ++i) {
int x = in.nextInt();
dq.add(x);
max = Math.max(max, x);
}
ArrayList<Pair> ans = new ArrayList<>();
while(dq.peekFirst() != max) {
int a = dq.pollFirst();
int b = dq.pollFirst();
ans.add(new Pair(a, b));
if(a > b) {
dq.addFirst(a);
dq.addLast(b);
}
else {
dq.addFirst(b);
dq.addLast(a);
}
}
ArrayList<Integer> a = new ArrayList<>();
dq.pollFirst();
for(int x : dq)
a.add(x);
while(q --> 0) {
long m = in.nextLong() - 1;
if(m < ans.size()) {
System.out.println(ans.get((int)m).first + " " + ans.get((int)m).second);
}
else {
int idx = (int)((m - ans.size()) % a.size());
System.out.println(max + " " + a.get(idx));
}
}
out.close();
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static boolean nextPermutation(int[] a) {
for(int i = a.length - 2; i >= 0; --i) {
if(a[i] < a[i+1]) {
for(int j = a.length - 1; ; --j) {
if(a[i] < a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
for(i++, j = a.length - 1; i < j; ++i, --j) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
return true;
}
}
}
}
return false;
}
static void shuffle(int[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
int t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(long[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
long t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static int lower_bound(int[] a, int n, int k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
super();
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return this.first != o.first ? this.first - o.first : this.second - o.second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
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 {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
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 String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
|
n
|
1008.java
| 0.5 |
import java.util.*;
public class Kello
{
public static void main(String args[])
{
Scanner sc =new Scanner(System.in);
int n,q,m,max,inp,k,i;
long in_q;
n=sc.nextInt();
q=sc.nextInt();
int a[]=new int[n-1];
int b[]=new int[n-1];
int c[]=new int[n-1];
max=sc.nextInt();
for(i=0;i<n-1;i++)
{
inp=sc.nextInt();
a[i]=max;
b[i]=inp;
if(inp>max)
{
c[i]=max;
max=inp;
}
else
c[i]=inp;
}
// display(a,b);
for(i=0;i<q;i++)
{
in_q=sc.nextLong();
if(in_q<n)
System.out.println(a[(int)in_q-1]+" "+b[(int)in_q-1]);
else {
k=(int)(in_q %(n-1))-1;
if(k==-1)
k=n-2;
System.out.println(max+" "+c[k]);
}
}
}
public static void display(int a[],int b[])
{
int i;
for(i=0;i<a.length;i++)
System.out.println(a[i]+" "+b[i]);
}
}
|
n
|
1009.java
| 0.5 |
// Java program to find the Minimum length Unsorted Subarray,
// sorting which makes the complete array sorted
class
Main
{
static
void
printUnsorted(
int
arr[],
int
n)
{
int
s =
0
, e = n-
1
, i, max, min;
// step 1(a) of above algo
for
(s =
0
; s < n-
1
; s++)
{
if
(arr[s] > arr[s+
1
])
break
;
}
if
(s == n-
1
)
{
System.out.println(
"The complete array is sorted"
);
return
;
}
// step 1(b) of above algo
for
(e = n -
1
; e >
0
; e--)
{
if
(arr[e] < arr[e-
1
])
break
;
}
// step 2(a) of above algo
max = arr[s]; min = arr[s];
for
(i = s +
1
; i <= e; i++)
{
if
(arr[i] > max)
max = arr[i];
if
(arr[i] < min)
min = arr[i];
}
// step 2(b) of above algo
for
( i =
0
; i < s; i++)
{
if
(arr[i] > min)
{
s = i;
break
;
}
}
// step 2(c) of above algo
for
( i = n -
1
; i >= e+
1
; i--)
{
if
(arr[i] < max)
{
e = i;
break
;
}
}
// step 3 of above algo
System.out.println(
" The unsorted subarray which"
+
" makes the given array sorted lies"
+
" between the indices "
+s+
" and "
+e);
return
;
}
public
static
void
main(String args[])
{
int
arr[] = {
10
,
12
,
20
,
30
,
25
,
40
,
32
,
31
,
35
,
50
,
60
};
int
arr_size = arr.length;
printUnsorted(arr, arr_size);
}
}
|
n
|
101.java
| 0.5 |
import java.io.*;
import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.InputMismatchException;
import java.util.StringTokenizer;
public class C {
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
BigInteger nextBigInteger() {
try {
return new BigInteger(nextLine());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
}
public static void main(String[] args) {
FastReader fr = new FastReader();
FastWriter fw = new FastWriter();
int n = fr.nextInt();
int q = fr.nextInt();
int[] aa = new int[n - 1];
int[] ab = new int[n - 1];
Deque<Integer> dq = new ArrayDeque<>();
for (int i = 0; i < n; i++) dq.addLast(fr.nextInt());
for (int i = 0; i < n - 1; i++) {
int a = dq.removeFirst();
int b = dq.removeFirst();
aa[i] = a;
ab[i] = b;
int mi = Math.min(a, b);
int ma = Math.max(a, b);
dq.addFirst(ma);
dq.addLast(mi);
}
int fm = dq.removeFirst();
int[] arr = new int[n - 1];
for (int i = 0; i < arr.length; i++) arr[i] = dq.removeFirst();
while (q-- > 0) {
long m = fr.nextLong() - 1;
if (m < n - 1) {
System.out.println(aa[(int) m] + " " + ab[(int) m]);
} else {
m = m % (n - 1);
System.out.println(fm + " " + arr[(int) m]);
}
}
}
}
|
n
|
1010.java
| 0.5 |
import java.io.*;
import java.util.*;
public class Main
{
class node{
int data;
node next;
public node(int val){
data=val;
next=null;
}
}
class linkedlist{
node start;
node end;
int size;
int turn;
public linkedlist(){
start=null;
end=null;
size=0;
}
void add(int val){
if(size==0){
node t=new node(val);
start=t;
end=t;
size++;
}
else{
node t=new node(val);
end.next=t;
end=end.next;
size++;
}
}
void myfunc(){
if(start.data>start.next.data){
// System.out.println("me ni hu");
node t=new node(start.next.data);
start.next=start.next.next;
end.next=t;
end=end.next;
}
else{
// System.out.println("me hu");
int t=start.data;
start=start.next;
add(t);
size--;
}
}
int findmax(){
int m=0;
node temp=start;
for(int i=0;i<size;i++){
if(temp.data>m){
m=temp.data;
}
temp=temp.next;
}
return m;
}
void display(){
node temp=start;
for(int i=0;i<size;i++){
System.out.print(temp.data+" ");
temp=temp.next;
}
System.out.println("");
}
}
linkedlist l;
public Main(){
l=new linkedlist();
}
public static void main(String [] argv) throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Main ma=new Main();
String[] l1=in.readLine().split(" ");
int n=Integer.parseInt(l1[0]);
int q=Integer.parseInt(l1[1]);
String[] ar=in.readLine().split(" ");
int a1=Integer.parseInt(ar[0]);
int b1=Integer.parseInt(ar[1]);
for(int i=0;i<n;i++){
ma.l.add(Integer.parseInt(ar[i]));
}
int m=ma.l.findmax();
int[][] pair=new int[n][2];
int t=0;
for(int i=0;i<n;i++){
if(ma.l.start.data==m)
break;
ma.l.myfunc();
pair[t][0]=ma.l.start.data;
pair[t][1]=ma.l.start.next.data;
t++;
}
int rl[]=new int[n];
node temp=ma.l.start;
for(int i=0;i<n;i++){
rl[i]=temp.data;
temp=temp.next;
}
for(int i=0;i<q;i++){
long a=Long.parseLong(in.readLine());
if(a==1){
System.out.println(a1 + " " + b1);
}
else{
if(a<=t+1){
System.out.println(pair[(int)(a-2)][0]+" "+pair[(int)(a-2)][1]);
}
else{
if((a-t)%(n-1)==0){
System.out.println(rl[0]+" "+rl[n-1]);
}
else{
System.out.println(rl[0]+" "+rl[(int)((a-t)%(n-1))]);
}
}
}
}
}
}
|
n
|
1011.java
| 0.5 |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class C {
void solve(){
int n = readInt();
int q = readInt();
int max = 0;
int[] a = new int[n];
Deque<Integer> deque = new ArrayDeque<>();
for(int i = 0;i<n;i++){
a[i] = readInt();
deque.addLast(a[i]);
max = Math.max(max, a[i]);
}
List<String> ans = new ArrayList<>();
while(deque.peekFirst() != max){
int one = deque.pollFirst();
int two = deque.pollFirst();
ans.add(one + " " + two);
deque.addFirst(one > two ? one : two);
deque.addLast(one > two ? two : one);
if(one == max) break;
}
for(int i = 0;i<n;i++){
a[i] = deque.pollFirst();
}
for(int i = 0;i<q;i++){
long x = readLong();
if(x <= ans.size()){
out.println(ans.get((int)x - 1));
continue;
}
x -= ans.size();
int y =(int) (x%(n - 1) - 1%(n - 1) + (n - 1)) % (n - 1) + 1;
out.println(max + " " + a[y]);
}
}
public static void main(String[] args) {
new C().run();
}
void run(){
init();
solve();
out.close();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init(){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
String readLine(){
try{
return in.readLine();
}catch(Exception ex){
throw new RuntimeException(ex);
}
}
String readString(){
while(!tok.hasMoreTokens()){
String nextLine = readLine();
if(nextLine == null) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken();
}
int readInt(){
return Integer.parseInt(readString());
}
long readLong(){
return Long.parseLong(readString());
}
double readDouble(){
return Double.parseDouble(readString());
}
}
|
n
|
1012.java
| 0.5 |
import java.io.*;
import java.util.*;
import java.lang.*;
import java.awt.*;
import java.awt.geom.*;
import java.math.*;
import java.text.*;
import java.math.BigInteger.*;
import java.util.Arrays;
public class CF111111
{
BufferedReader in;
StringTokenizer as;
int nums[],nums2[];
int[] nums1[];
boolean con = true;
ArrayList < Integer > ar = new ArrayList < Integer >();
ArrayList < Integer > fi = new ArrayList < Integer >();
Map<Integer,Integer > map = new HashMap<Integer, Integer>();
public static void main (String[] args)
{
new CF111111 ();
}
public int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
public int LIS(int arr[])
{
int n = arr.length;
int sun[] = new int [n];
int cur = 0;
for(int x = 0;x<n;x++)
{
int temp = Arrays.binarySearch(sun,0,cur,arr[x]);
if(temp < 0)
temp = -temp -1;
sun[temp] = arr[x];
if(temp == cur)
cur++;
}
return cur;
}
public CF111111 ()
{
try
{
in = new BufferedReader (new InputStreamReader (System.in));
int a = nextInt();
for(int xx1 = 0;xx1<a;xx1++)
{
int b = nextInt();
nums = new int [b];
for(int x = 0;x<b;x++)
{
nums[x] = nextInt();
}
int max = 0;
int max2 = -1;
for(int x = 0;x<b;x++)
{
if(nums[x] >= max)
{
max2 = max;
max = nums[x];
}
else if(nums[x] >= max2)
max2 = nums[x];
}
System.out.println(Math.min(max2, b-1)-1);
}
}
catch(IOException e)
{
}
}
String next () throws IOException
{
while (as == null || !as.hasMoreTokens ())
{
as = new StringTokenizer (in.readLine ().trim ());
}
return as.nextToken ();
}
long nextLong () throws IOException
{
return Long.parseLong (next ());
}
int nextInt () throws IOException
{
return Integer.parseInt (next ());
}
double nextDouble () throws IOException
{
return Double.parseDouble (next ());
}
String nextLine () throws IOException
{
return in.readLine ().trim ();
}
}
|
n
|
1021.java
| 0.5 |
import java.util.*;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
for(; T > 0; T--) {
int n = scan.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++) arr[i] = scan.nextInt();
int m1 = 1, m2 = 1;
for(int i = 0; i < n; i++) {
if(arr[i] >= m1) {
m2 = m1;
m1 = arr[i];
} else if (arr[i] >= m2) {
m2 = arr[i];
}
}
System.out.println(Math.min(Math.min(m1, m2) - 1, n - 2));
}
}
}
|
n
|
1022.java
| 0.5 |
import java.util.*;
import java.io.*;
import java.math.*;
public class Solution{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
StringTokenizer st;
for(int z=0;z<t;z++){
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
int min=1;
int max=1;
for(int i=0;i<n;i++){
int k = Integer.parseInt(st.nextToken());
if(max<k){
min = max;
max = k;
}else if(min<k){
min = k;
}
}
int res = Math.min(n-2,min-1);
System.out.println(res);
}
}
}
|
n
|
1023.java
| 0.5 |
import java.io.*;
import java.util.*;
import java.lang.*;
import java.awt.*;
import java.awt.geom.*;
import java.math.*;
import java.text.*;
import java.math.BigInteger.*;
import java.util.Arrays;
public class CF111111
{
BufferedReader in;
StringTokenizer as;
int nums[],nums2[];
int[] nums1[];
boolean con = true;
ArrayList < Integer > ar = new ArrayList < Integer >();
ArrayList < Integer > fi = new ArrayList < Integer >();
Map<Integer,Integer > map = new HashMap<Integer, Integer>();
public static void main (String[] args)
{
new CF111111 ();
}
public int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
public int LIS(int arr[])
{
int n = arr.length;
int sun[] = new int [n];
int cur = 0;
for(int x = 0;x<n;x++)
{
int temp = Arrays.binarySearch(sun,0,cur,arr[x]);
if(temp < 0)
temp = -temp -1;
sun[temp] = arr[x];
if(temp == cur)
cur++;
}
return cur;
}
public void no()
{
System.out.println("NO");
System.exit(0);
}
public CF111111 ()
{
try
{
in = new BufferedReader (new InputStreamReader (System.in));
int a = nextInt();
nums = new int [a];
int max = -1;
int index = -1;
for(int x = 0;x<a;x++)
{
nums[x] = nextInt();
if(nums[x] > max)
{
max = nums[x];
index = x;
}
}
int lindex = index-1;
int rindex = index+1;
int done = 1;
int top = max;
for(;;)
{
done++;
// System.out.println(done + " " + lindex + " " + rindex);
if(lindex < 0)
{
if(nums[rindex] > top)
{
no();
}
else
top = nums[rindex];
rindex++;
}
else if(rindex >= a)
{
if(nums[lindex] > top)
no();
else
top = nums[lindex];
lindex--;
}
else
{
if(nums[lindex] > top || nums[rindex] > top)
no();
else
{
if(nums[lindex] > nums[rindex])
{
top = nums[lindex];
lindex--;
}
else
{
top = nums[rindex];
rindex++;
}
}
}
if(done == a)
{
System.out.println("YES");
System.exit(0);
}
}
}
catch(IOException e)
{
}
}
String next () throws IOException
{
while (as == null || !as.hasMoreTokens ())
{
as = new StringTokenizer (in.readLine ().trim ());
}
return as.nextToken ();
}
long nextLong () throws IOException
{
return Long.parseLong (next ());
}
int nextInt () throws IOException
{
return Integer.parseInt (next ());
}
double nextDouble () throws IOException
{
return Double.parseDouble (next ());
}
String nextLine () throws IOException
{
return in.readLine ().trim ();
}
}
|
n
|
1025.java
| 0.5 |
import java.util.Scanner;
public class pillar {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[200005];
for (int i=1;i<=n;i++)
a[i]=sc.nextInt();
for (int i=2;i<n;i++)
if (a[i-1]>a[i]&&a[i]<a[i+1]) {
System.out.println("NO");
return;
}
System.out.println("YES");
}
}
|
n
|
1026.java
| 0.5 |
import java.util.*;
import java.io.*;
import java.math.*;
public class Solution{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] a = new int[n];
for(int i=0;i<n;i++) a[i] = Integer.parseInt(st.nextToken());
int ind = 0;
for(int i=0;i<n;i++){
if(a[i]==n){
ind = i;
break;
}
}
boolean ok = true;
for(int i=ind+1;i<n;i++) if(a[i]>a[i-1]) ok = false;
for(int i=ind-1;i>=0;i--) if(a[i]>a[i+1]) ok = false;
if(ok) System.out.println("YES");
else System.out.println("NO");
}
}
|
n
|
1027.java
| 0.5 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class CF1197B {
public static void main(String[] args) {
FastReader input = new FastReader();
int n = input.nextInt();
int[] arr = new int[n];
int max = 0;
int maxIndex = 0;
for(int i = 0;i < n;i++){
arr[i] = input.nextInt();
if(arr[i] > max){
max = arr[i];
maxIndex = i;
}
}
int j = maxIndex - 1;
int k = maxIndex + 1;
while (j >= 0 && k < n){
if(arr[j] > arr[k]){
if(arr[j] < max){
max = arr[j];
j--;
}
else {
System.out.println("NO");
return;
}
}
else{
if(arr[k] < max){
max = arr[k];
k++;
}
else{
System.out.println("NO");
return;
}
}
}
if(j >= 0){
while (j >= 0){
if(arr[j] < max){
max = arr[j];
j--;
}
else{
System.out.println("NO");
return;
}
}
}
if(k < n){
while (k < n){
if(arr[k] < max){
max = arr[k];
k++;
}
else{
System.out.println("NO");
return;
}
}
}
if(j == -1 && k == n){
System.out.println("YES");
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
n
|
1028.java
| 0.5 |
import java.io.*;
import java.util.*;
public class codef
{
public static void main(String ar[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
String st[]=br.readLine().split(" ");
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=Integer.parseInt(st[i]);
int max=0;
for(int i=0;i<n;i++)
{
if(i!=0 && a[i]>a[max])
max=i;
}
// System.out.println(a[max]);
int maxi=max;
int i=max-1;
while(i>=0)
{
if(a[i]>a[max])
{
System.out.println("NO");
return;
}
max=i;
i--;
}
max=maxi;
i=max+1;
while(i<n)
{
if(a[i]>a[max])
{
System.out.println("NO");
return;
}
max=i;
i++;
}
System.out.println("YES");
}
}
|
n
|
1029.java
| 0.5 |
import
java.io.*;
class
PairSum {
// Fills element in arr[] from its pair sum array pair[].
// n is size of arr[]
static
void
constructArr(
int
arr[],
int
pair[],
int
n)
{
arr[
0
] = (pair[
0
]+pair[
1
]-pair[n-
1
]) /
2
;
for
(
int
i=
1
; i<n; i++)
arr[i] = pair[i-
1
]-arr[
0
];
}
// Driver program to test above function
public
static
void
main(String[] args)
{
int
pair[] = {
15
,
13
,
11
,
10
,
12
,
10
,
9
,
8
,
7
,
5
};
int
n =
5
;
int
[] arr =
new
int
[n];
constructArr(arr, pair, n);
for
(
int
i =
0
; i < n; i++)
System.out.print(arr[i]+
" "
);
}
}
/* This code is contributed by Devesh Agrawal */
|
n
|
106.java
| 0.5 |
// Java program to calculate the
// product of max element of first
// array and min element of second array
import
java.util.*;
import
java.lang.*;
class
GfG
{
// Function to calculate the product
public
static
int
minMaxProduct(
int
arr1[],
int
arr2[],
int
n1,
int
n2)
{
// Initialize max of
// first array
int
max = arr1[
0
];
// initialize min of
// second array
int
min = arr2[
0
];
int
i;
for
(i =
1
; i < n1 && i < n2; ++i)
{
// To find the maximum
// element in first array
if
(arr1[i] > max)
max = arr1[i];
// To find the minimum element
// in second array
if
(arr2[i] < min)
min = arr2[i];
}
// Process remaining elements
while
(i < n1)
{
if
(arr1[i] > max)
max = arr1[i];
i++;
}
while
(i < n2)
{
if
(arr2[i] < min)
min = arr2[i];
i++;
}
return
max * min;
}
// Driver Code
public
static
void
main(String argc[])
{
int
[] arr1=
new
int
[]{
10
,
2
,
3
,
6
,
4
,
1
};
int
[] arr2 =
new
int
[]{
5
,
1
,
4
,
2
,
6
,
9
};
int
n1 =
6
;
int
n2 =
6
;
System.out.println(minMaxProduct(arr1, arr2,
n1, n2));
}
}
// This code is contributed by Sagar Shukla
|
n
|
109.java
| 0.5 |
// Java Program to find all the common characters
// in n strings
import
java.util.*;
import
java.lang.*;
class
GFG {
static
int
MAX_CHAR =
26
;
public
static
void
commonCharacters(String str[],
int
n)
{
// primary array for common characters
// we assume all characters are seen before.
Boolean[] prim =
new
Boolean[MAX_CHAR];
Arrays.fill(prim,
new
Boolean(
true
));
// for each string
for
(
int
i =
0
; i < n; i++) {
// secondary array for common characters
// Initially marked false
Boolean[] sec =
new
Boolean[MAX_CHAR];
Arrays.fill(sec,
new
Boolean(
false
));
// for every character of ith string
for
(
int
j =
0
; j < str[i].length(); j++)
{
// if character is present in all
// strings before, mark it.
if
(prim[str[i].charAt(j) -
'a'
])
sec[str[i].charAt(j) -
'a'
] =
true
;
}
// copy whole secondary array into primary
System.arraycopy(sec,
0
, prim,
0
, MAX_CHAR);
}
// displaying common characters
for
(
int
i =
0
; i <
26
; i++)
if
(prim[i]){
System.out.print(Character.toChars(i
+
97
));
System.out.print(
" "
);
}
}
// Driver code
public
static
void
main(String[] args)
{
String str[] = {
"geeksforgeeks"
,
"gemkstones"
,
"acknowledges"
,
"aguelikes"
};
int
n = str.length;
commonCharacters(str, n);
}
}
// This code is contributed by Prasad Kshirsagar
|
n
|
268.java
| 0.5 |
// Java implementation to find the uncommon
// characters of the two strings
class
GFG
{
// size of the hash table
static
int
MAX_CHAR =
26
;
// function to find the uncommon
// characters of the two strings
static
void
findAndPrintUncommonChars(String str1,
String str2)
{
// mark presence of each character as 0
// in the hash table 'present[]'
int
present[] =
new
int
[MAX_CHAR];
for
(
int
i =
0
; i < MAX_CHAR; i++)
{
present[i] =
0
;
}
int
l1 = str1.length();
int
l2 = str2.length();
// for each character of str1, mark its
// presence as 1 in 'present[]'
for
(
int
i =
0
; i < l1; i++)
{
present[str1.charAt(i) -
'a'
] =
1
;
}
// for each character of str2
for
(
int
i =
0
; i < l2; i++)
{
// if a character of str2 is also present
// in str1, then mark its presence as -1
if
(present[str2.charAt(i) -
'a'
] ==
1
|| present[str2.charAt(i) -
'a'
] == -
1
)
{
present[str2.charAt(i) -
'a'
] = -
1
;
}
// else mark its presence as 2
else
{
present[str2.charAt(i) -
'a'
] =
2
;
}
}
// print all the uncommon characters
for
(
int
i =
0
; i < MAX_CHAR; i++)
{
if
(present[i] ==
1
|| present[i] ==
2
)
{
System.out.print((
char
) (i +
'a'
) +
" "
);
}
}
}
// Driver code
public
static
void
main(String[] args)
{
String str1 =
"characters"
;
String str2 =
"alphabets"
;
findAndPrintUncommonChars(str1, str2);
}
}
// This code is contributed by Rajput-JI
|
n
|
269.java
| 0.5 |
// Java implementation of alternate vowel and
// consonant string
import
java.util.*;
class
GFG
{
// 'ch' is vowel or not
static
boolean
isVowel(
char
ch)
{
if
(ch ==
'a'
|| ch ==
'e'
|| ch ==
'i'
||
ch ==
'o'
|| ch ==
'u'
)
return
true
;
return
false
;
}
// create alternate vowel and consonant string
// str1[0...l1-1] and str2[start...l2-1]
static
String createAltStr(String str1, String str2,
int
start,
int
l)
{
String finalStr =
""
;
// first adding character of vowel/consonant
// then adding character of consonant/vowel
for
(
int
i =
0
, j = start; j < l; i++, j++)
finalStr = (finalStr + str1.charAt(i)) +
str2.charAt(j);
return
finalStr;
}
// function to find the required
// alternate vowel and consonant string
static
String findAltStr(String str)
{
int
nv =
0
, nc =
0
;
String vstr =
""
, cstr =
""
;
int
l = str.length();
for
(
int
i =
0
; i < l; i++)
{
char
ch = str.charAt(i);
// count vowels and updaye vowel string
if
(isVowel(ch))
{
nv++;
vstr = vstr + ch;
}
// count consonants and update consonant
// string
else
{
nc++;
cstr = cstr + ch;
}
}
// no such string can be formed
if
(Math.abs(nv - nc) >=
2
)
return
"no such string"
;
// remove first character of vowel string
// then create alternate string with
// cstr[0...nc-1] and vstr[1...nv-1]
if
(nv > nc)
return
(vstr.charAt(
0
) + createAltStr(cstr, vstr,
1
, nv));
// remove first character of consonant string
// then create alternate string with
// vstr[0...nv-1] and cstr[1...nc-1]
if
(nc > nv)
return
(cstr.charAt(
0
) + createAltStr(vstr, cstr,
1
, nc));
// if both vowel and consonant
// strings are of equal length
// start creating string with consonant
if
(cstr.charAt(
0
) < vstr.charAt(
0
))
return
createAltStr(cstr, vstr,
0
, nv);
// start creating string with vowel
return
createAltStr(vstr, cstr,
0
, nc);
}
// Driver code
public
static
void
main(String args[])
{
String str =
"geeks"
;
System.out.println(findAltStr(str));
}
}
// This code is contributed by
// Shashank_Sharma
|
n
|
270.java
| 0.5 |
// A O(n) C++ program to count number of substrings
//starting and ending with 1
class
CountSubString
{
int
countSubStr(
char
str[],
int
n)
{
int
m =
0
;
// Count of 1's in input string
// Traverse input string and count of 1's in it
for
(
int
i =
0
; i < n; i++)
{
if
(str[i] ==
'1'
)
m++;
}
// Return count of possible pairs among m 1's
return
m * (m -
1
) /
2
;
}
// Driver program to test the above function
public
static
void
main(String[] args)
{
CountSubString count =
new
CountSubString();
String string =
"00100101"
;
char
str[] = string.toCharArray();
int
n = str.length;
System.out.println(count.countSubStr(str, n));
}
}
|
n
|
272.java
| 0.5 |
// Java program to get same frequency character
// string by removal of at most one char
public
class
GFG {
static
final
int
M =
26
;
// Utility method to get index of character ch
// in lower alphabet characters
static
int
getIdx(
char
ch)
{
return
(ch -
'a'
);
}
// Returns true if all non-zero elements
// values are same
static
boolean
allSame(
int
freq[],
int
N)
{
int
same =
0
;
// get first non-zero element
int
i;
for
(i =
0
; i < N; i++) {
if
(freq[i] >
0
) {
same = freq[i];
break
;
}
}
// check equality of each element with
// variable same
for
(
int
j = i +
1
; j < N; j++)
if
(freq[j] >
0
&& freq[j] != same)
return
false
;
return
true
;
}
// Returns true if we can make all character
// frequencies same
static
boolean
possibleSameCharFreqByOneRemoval(String str)
{
int
l = str.length();
// fill frequency array
int
[] freq =
new
int
[M];
for
(
int
i =
0
; i < l; i++)
freq[getIdx(str.charAt(i))]++;
// if all frequencies are same, then return true
if
(allSame(freq, M))
return
true
;
/* Try decreasing frequency of all character
by one and then check all equality of all
non-zero frequencies */
for
(
char
c =
'a'
; c <=
'z'
; c++) {
int
i = getIdx(c);
// Check character only if it occurs in str
if
(freq[i] >
0
) {
freq[i]--;
if
(allSame(freq, M))
return
true
;
freq[i]++;
}
}
return
false
;
}
// Driver code to test above methods
public
static
void
main(String args[])
{
String str =
"xyyzz"
;
if
(possibleSameCharFreqByOneRemoval(str))
System.out.println(
"Yes"
);
else
System.out.println(
"No"
);
}
}
// This code is contributed by Sumit Ghosh
|
n
|
273.java
| 0.5 |
// Java implementation to find the character in
// first string that is present at minimum index
// in second string
import
java.util.HashMap;
public
class
GFG
{
// method to find the minimum index character
static
void
printMinIndexChar(String str, String patt)
{
// map to store the first index of each character of 'str'
HashMap<Character, Integer> hm =
new
HashMap<>();
// to store the index of character having
// minimum index
int
minIndex = Integer.MAX_VALUE;
// lengths of the two strings
int
m = str.length();
int
n = patt.length();
// store the first index of each character of 'str'
for
(
int
i =
0
; i < m; i++)
if
(!hm.containsKey(str.charAt(i)))
hm.put(str.charAt(i),i);
// traverse the string 'patt'
for
(
int
i =
0
; i < n; i++)
// if patt[i] is found in 'um', check if
// it has the minimum index or not accordingly
// update 'minIndex'
if
(hm.containsKey(patt.charAt(i)) &&
hm.get(patt.charAt(i)) < minIndex)
minIndex = hm.get(patt.charAt(i));
// print the minimum index character
if
(minIndex != Integer.MAX_VALUE)
System.out.println(
"Minimum Index Character = "
+
str.charAt(minIndex));
// if no character of 'patt' is present in 'str'
else
System.out.println(
"No character present"
);
}
// Driver Method
public
static
void
main(String[] args)
{
String str =
"geeksforgeeks"
;
String patt =
"set"
;
printMinIndexChar(str, patt);
}
}
|
n
|
275.java
| 0.5 |
// Java program to remove duplicates, the order of
// characters is not maintained in this program
public
class
GFG
{
static
final
int
NO_OF_CHARS =
256
;
/* Returns an array of size 256 containg count
of characters in the passed char array */
static
int
[] getCharCountArray(String str)
{
int
count[] =
new
int
[NO_OF_CHARS];
for
(
int
i =
0
; i<str.length(); i++)
count[str.charAt(i)]++;
return
count;
}
/* removeDirtyChars takes two string as arguments: First
string (str) is the one from where function removes dirty
characters. Second string is the string which contain all
dirty characters which need to be removed from first string */
static
String removeDirtyChars(String str, String mask_str)
{
int
count[] = getCharCountArray(mask_str);
int
ip_ind =
0
, res_ind =
0
;
char
arr[] = str.toCharArray();
while
(ip_ind != arr.length)
{
char
temp = arr[ip_ind];
if
(count[temp] ==
0
)
{
arr[res_ind] = arr[ip_ind];
res_ind ++;
}
ip_ind++;
}
str =
new
String(arr);
/* After above step string is ngring.
Removing extra "iittg" after string*/
return
str.substring(
0
, res_ind);
}
// Driver Method
public
static
void
main(String[] args)
{
String str =
"geeksforgeeks"
;
String mask_str =
"mask"
;
System.out.println(removeDirtyChars(str, mask_str));
}
}
|
n
|
276.java
| 0.5 |
// Java implementation of program to find
// the maximum length that can be removed
import
java.util.ArrayList;
public
class
GFG
{
// User defined class Pair
static
class
Pair{
char
first;
int
second;
Pair(
char
first,
int
second){
this
.first = first;
this
.second = second;
}
}
/* Function to find the length of longest
sub-string that can me make removed
arr --> pair type of array whose first
field store character in string
and second field stores
corresponding index of that character*/
static
int
longestNull(String str)
{
ArrayList<Pair> arr =
new
ArrayList<>();
// store {'@',-1} in arr , here this value
// will work as base index
arr.add(
new
Pair(
'@'
, -
1
));
int
maxlen =
0
;
// Initialize result
// one by one iterate characters of string
for
(
int
i =
0
; i < str.length(); ++i)
{
// make pair of char and index , then
// store them into arr
arr.add(
new
Pair(str.charAt(i), i));
// now if last three elements of arr[]
// are making sub-string "100" or not
while
(arr.size() >=
3
&&
arr.get(arr.size()-
3
).first==
'1'
&&
arr.get(arr.size()-
2
).first==
'0'
&&
arr.get(arr.size()-
1
).first==
'0'
)
{
// if above condition is true then
// delete sub-string "100" from arr[]
arr.remove(arr.size() -
3
);
arr.remove(arr.size() -
2
);
arr.remove(arr.size() -
1
);
}
// index of current last element in arr[]
int
tmp = arr.get(arr.size() -
1
).second;
// This is important, here 'i' is the index
// of current character inserted into arr[]
// and 'tmp' is the index of last element
// in arr[] after continuous deletion of
// sub-string "100" from arr[] till we make
// it null, difference of these to 'i-tmp'
// gives the length of current sub-string
// that can be make null by continuous
// deletion of sub-string "100"
maxlen = Math.max(maxlen, i - tmp);
}
return
maxlen;
}
// Driver program to run the case
public
static
void
main(String args[])
{
System.out.println(longestNull(
"1011100000100"
));
}
}
// This code is contributed by Sumit Ghosh
|
n
|
277.java
| 0.5 |
// An otpimized Java program to find pairs with distance
// equal to English alphabet distance
class
Test {
static
final
int
MAX_CHAR =
26
;
// Method to count pairs with distance
// equal to English alphabet distance
static
int
countPairs(String str)
{
int
result =
0
;
int
n = str.length();
for
(
int
i =
0
; i < n; i++)
// This loop runs at most 26 times
for
(
int
j =
1
; (i + j) < n && j <= MAX_CHAR; j++)
if
((Math.abs(str.charAt(i + j) - str.charAt(i)) == j))
result++;
return
result;
}
// Driver method
public
static
void
main(String args[])
{
String str =
"geeksforgeeks"
;
System.out.println(countPairs(str));
}
}
|
n
|
279.java
| 0.5 |
// Recursive Java Program to reverse an array
import
java.io.*;
class
ReverseArray {
/* Function to reverse arr[] from start to end*/
static
void
rvereseArray(
int
arr[],
int
start,
int
end)
{
int
temp;
if
(start >= end)
return
;
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
rvereseArray(arr, start+
1
, end-
1
);
}
/* Utility that prints out an array on a line */
static
void
printArray(
int
arr[],
int
size)
{
for
(
int
i=
0
; i < size; i++)
System.out.print(arr[i] +
" "
);
System.out.println(
""
);
}
/*Driver function to check for above functions*/
public
static
void
main (String[] args) {
int
arr[] = {
1
,
2
,
3
,
4
,
5
,
6
};
printArray(arr,
6
);
rvereseArray(arr,
0
,
5
);
System.out.println(
"Reversed array is "
);
printArray(arr,
6
);
}
}
/*This article is contributed by Devesh Agrawal*/
|
n
|
28.java
| 0.5 |
// Java program to Find longest subsequence where
// every character appears at-least k times
class
GFG {
static
final
int
MAX_CHARS =
26
;
static
void
longestSubseqWithK(String str,
int
k) {
int
n = str.length();
// Count frequencies of all characters
int
freq[] =
new
int
[MAX_CHARS];
for
(
int
i =
0
; i < n; i++) {
freq[str.charAt(i) -
'a'
]++;
}
// Traverse given string again and print
// all those characters whose frequency
// is more than or equal to k.
for
(
int
i =
0
; i < n; i++) {
if
(freq[str.charAt(i) -
'a'
] >= k) {
System.out.print(str.charAt(i));
}
}
}
// Driver code
static
public
void
main(String[] args) {
String str =
"geeksforgeeks"
;
int
k =
2
;
longestSubseqWithK(str, k);
}
}
// This code is contributed by Rajput-Ji
|
n
|
280.java
| 0.5 |
// Java program to count subsequences of the
// form a^i b^j c^k
public
class
No_of_subsequence {
// Returns count of subsequences of the form
// a^i b^j c^k
static
int
countSubsequences(String s)
{
// Initialize counts of different subsequences
// caused by different combination of 'a'
int
aCount =
0
;
// Initialize counts of different subsequences
// caused by different combination of 'a' and
// different combination of 'b'
int
bCount =
0
;
// Initialize counts of different subsequences
// caused by different combination of 'a', 'b'
// and 'c'.
int
cCount =
0
;
// Traverse all characters of given string
for
(
int
i=
0
; i< s.length(); i++)
{
/* If current character is 'a', then
there are following possibilities :
a) Current character begins a new
subsequence.
b) Current character is part of aCount
subsequences.
c) Current character is not part of
aCount subsequences. */
if
(s.charAt(i) ==
'a'
)
aCount = (
1
+
2
* aCount);
/* If current character is 'b', then
there are following possibilities :
a) Current character begins a new
subsequence of b's with aCount
subsequences.
b) Current character is part of bCount
subsequences.
c) Current character is not part of
bCount subsequences. */
else
if
(s.charAt(i) ==
'b'
)
bCount = (aCount +
2
* bCount);
/* If current character is 'c', then
there are following possibilities :
a) Current character begins a new
subsequence of c's with bCount
subsequences.
b) Current character is part of cCount
subsequences.
c) Current character is not part of
cCount subsequences. */
else
if
(s.charAt(i) ==
'c'
)
cCount = (bCount +
2
* cCount);
}
return
cCount;
}
// Driver code
public
static
void
main(String args[])
{
String s =
"abbc"
;
System.out.println(countSubsequences(s));
}
}
// This code is contributed by Sumit Ghosh
|
n
|
281.java
| 0.5 |
// Java code to find number of subsequences of
// "ab" in the string S which is repeated K times.
import
java.io.*;
class
GFG {
static
int
countOccurrences(String s,
int
K)
{
int
n = s.length();
int
C =
0
, c1 =
0
, c2 =
0
;
for
(
int
i =
0
; i < n; i++) {
if
(s.charAt(i) ==
'a'
)
c1++;
// Count of 'a's
if
(s.charAt(i) ==
'b'
) {
c2++;
// Count of 'b's
// occurrence of "ab"s
// in string S
C += c1;
}
}
// Add following two :
// 1) K * (Occurrences of "ab" in single string)
// 2) a is from one string and b is from other.
return
C * K + (K * (K -
1
) /
2
) * c1 * c2;
}
// Driver code
public
static
void
main(String[] args)
{
String S =
"abcb"
;
int
k =
2
;
System.out.println(countOccurrences(S, k));
}
}
// This code is contributed by vt_m.
|
n
|
282.java
| 0.5 |
// Java Program to find the "GFG" subsequence
// in the given string
public
class
GFG {
static
int
max =
100
;
// Print the count of "GFG" subsequence
// in the string
static
void
countSubsequence(String s,
int
n)
{
int
cntG =
0
, cntF =
0
, result =
0
, C=
0
;
// Traversing the given string
for
(
int
i =
0
; i < n; i++) {
switch
(s.charAt(i)) {
// If the character is 'G',
// increment the count of 'G',
// increase the result and
// update the array.
case
'G'
:
cntG++;
result+=C;
break
;
// If the character is 'F',
// increment the count of 'F'
// and update the array.
case
'F'
:
cntF++;
C+=cntG;
break
;
// Ignore other character.
default
:
continue
;
}
}
System.out.println(result);
}
// Driver code
public
static
void
main(String args[]) {
String s=
"GFGFG"
;
int
n = s.length();
countSubsequence(s, n);
}
}
// This code is contributed by Sam007
|
n
|
283.java
| 0.5 |
// Java program to count number of distinct
// subsequences of a given string.
import
java.util.ArrayList;
import
java.util.Arrays;
public
class
Count_Subsequences {
static
final
int
MAX_CHAR =
256
;
// Returns count of distinct sunsequences of str.
static
int
countSub(String str)
{
// Create an array to store index
// of last
int
[] last =
new
int
[MAX_CHAR];
Arrays.fill(last, -
1
);
// Length of input string
int
n = str.length();
// dp[i] is going to store count of distinct
// subsequences of length i.
int
[] dp =
new
int
[n+
1
];
// Empty substring has only one subsequence
dp[
0
] =
1
;
// Traverse through all lengths from 1 to n.
for
(
int
i=
1
; i<=n; i++)
{
// Number of subsequences with substring
// str[0..i-1]
dp[i] =
2
*dp[i-
1
];
// If current character has appeared
// before, then remove all subsequences
// ending with previous occurrence.
if
(last[(
int
)str.charAt(i-
1
)] != -
1
)
dp[i] = dp[i] - dp[last[(
int
)str.charAt(i-
1
)]];
// Mark occurrence of current character
last[(
int
)str.charAt(i-
1
)] = (i-
1
);
}
return
dp[n];
}
// Driver code
public
static
void
main(String args[])
{
System.out.println(countSub(
"gfg"
));
}
}
// This code is contributed by Sumit Ghosh
|
n
|
284.java
| 0.5 |
// Java program to find nth ugly number
import
java.lang.Math;
class
UglyNumber
{
/* Function to get the nth ugly number*/
int
getNthUglyNo(
int
n)
{
int
ugly[] =
new
int
[n];
// To store ugly numbers
int
i2 =
0
, i3 =
0
, i5 =
0
;
int
next_multiple_of_2 =
2
;
int
next_multiple_of_3 =
3
;
int
next_multiple_of_5 =
5
;
int
next_ugly_no =
1
;
ugly[
0
] =
1
;
for
(
int
i =
1
; i < n; i++)
{
next_ugly_no = Math.min(next_multiple_of_2,
Math.min(next_multiple_of_3,
next_multiple_of_5));
ugly[i] = next_ugly_no;
if
(next_ugly_no == next_multiple_of_2)
{
i2 = i2+
1
;
next_multiple_of_2 = ugly[i2]*
2
;
}
if
(next_ugly_no == next_multiple_of_3)
{
i3 = i3+
1
;
next_multiple_of_3 = ugly[i3]*
3
;
}
if
(next_ugly_no == next_multiple_of_5)
{
i5 = i5+
1
;
next_multiple_of_5 = ugly[i5]*
5
;
}
}
/*End of for loop (i=1; i<n; i++) */
return
next_ugly_no;
}
/* Driver program to test above functions */
public
static
void
main(String args[])
{
int
n =
150
;
UglyNumber obj =
new
UglyNumber();
System.out.println(obj.getNthUglyNo(n));
}
}
// This code has been contributed by Amit Khandelwal (Amit Khandelwal 1)
|
n
|
287.java
| 0.5 |
// A O(n) solution that uses
// table fact[] to calculate
// the Permutation Coefficient
import
java .io.*;
public
class
GFG {
// Returns value of Permutation
// Coefficient P(n, k)
static
int
permutationCoeff(
int
n,
int
k)
{
int
[]fact =
new
int
[n+
1
];
// base case
fact[
0
] =
1
;
// Caculate value
// factorials up to n
for
(
int
i =
1
; i <= n; i++)
fact[i] = i * fact[i -
1
];
// P(n,k) = n! / (n - k)!
return
fact[n] / fact[n - k];
}
// Driver Code
static
public
void
main (String[] args)
{
int
n =
10
, k =
2
;
System.out.println(
"Value of"
+
" P( "
+ n +
", "
+ k +
") is "
+ permutationCoeff(n, k) );
}
}
// This code is contributed by anuj_67.
|
n
|
296.java
| 0.5 |
// Java program for solution of
// friends pairing problem
import
java.io.*;
class
GFG {
// Returns count of ways n people
// can remain single or paired up.
static
int
countFriendsPairings(
int
n)
{
int
dp[] =
new
int
[n +
1
];
// Filling dp[] in bottom-up manner using
// recursive formula explained above.
for
(
int
i =
0
; i <= n; i++) {
if
(i <=
2
)
dp[i] = i;
else
dp[i] = dp[i -
1
] + (i -
1
) * dp[i -
2
];
}
return
dp[n];
}
// Driver code
public
static
void
main(String[] args)
{
int
n =
4
;
System.out.println(countFriendsPairings(n));
}
}
// This code is contributed by vt_m
|
n
|
299.java
| 0.5 |
import
java.util.Arrays;
public
class
Test
{
static
int
arr[] =
new
int
[]{
1
,
2
,
3
,
4
,
5
};
// Method for rotation
static
void
rotate()
{
int
x = arr[arr.length-
1
], i;
for
(i = arr.length-
1
; i >
0
; i--)
arr[i] = arr[i-
1
];
arr[
0
] = x;
}
/* Driver program */
public
static
void
main(String[] args)
{
System.out.println(
"Given Array is"
);
System.out.println(Arrays.toString(arr));
rotate();
System.out.println(
"Rotated Array is"
);
System.out.println(Arrays.toString(arr));
}
}
|
n
|
3.java
| 0.5 |
// Java program for solution of friends
// pairing problem Using Recursion
class
GFG {
static
int
[] dp =
new
int
[
1000
];
// Returns count of ways n people
// can remain single or paired up.
static
int
countFriendsPairings(
int
n)
{
if
(dp[n] != -
1
)
return
dp[n];
if
(n >
2
)
return
dp[n] = countFriendsPairings(n -
1
) + (n -
1
) * countFriendsPairings(n -
2
);
else
return
dp[n] = n;
}
// Driver code
public
static
void
main(String[] args)
{
for
(
int
i =
0
; i <
1000
; i++)
dp[i] = -
1
;
int
n =
4
;
System.out.println(countFriendsPairings(n));
}
}
// This code is contributed by Ita_c.
|
n
|
300.java
| 0.5 |
// Java program to find nth
// element of Newman-Conway Sequence
import
java.io.*;
class
GFG {
// Recursion to find
// n-th element
static
int
sequence(
int
n)
{
if
(n ==
1
|| n ==
2
)
return
1
;
else
return
sequence(sequence(n -
1
))
+ sequence(n - sequence(n -
1
));
}
// Driver Program
public
static
void
main(String args[])
{
int
n =
10
;
System.out.println(sequence(n));
}
}
/*This code is contributed by Nikita Tiwari.*/
|
n
|
308.java
| 0.5 |
// JAVA Code for Newman-Conway Sequence
import
java.util.*;
class
GFG {
// Function to find the n-th element
static
int
sequence(
int
n)
{
// Declare array to store sequence
int
f[] =
new
int
[n +
1
];
f[
0
] =
0
;
f[
1
] =
1
;
f[
2
] =
1
;
int
i;
for
(i =
3
; i <= n; i++)
f[i] = f[f[i -
1
]] +
f[i - f[i -
1
]];
return
f[n];
}
/* Driver program to test above function */
public
static
void
main(String[] args)
{
int
n =
10
;
System.out.println(sequence(n));
}
}
// This code is contributed by Arnav Kr. Mandal.
|
n
|
309.java
| 0.5 |
// A simple Java program to rearrange contents of arr[]
// such that arr[j] becomes j if arr[i] is j
class
RearrangeArray {
// A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]'
// becomes 'i' if 'arr[i]' is 'j'
void
rearrangeNaive(
int
arr[],
int
n)
{
// Create an auxiliary array of same size
int
temp[] =
new
int
[n];
int
i;
// Store result in temp[]
for
(i =
0
; i < n; i++)
temp[arr[i]] = i;
// Copy temp back to arr[]
for
(i =
0
; i < n; i++)
arr[i] = temp[i];
}
// A utility function to print contents of arr[0..n-1]
void
printArray(
int
arr[],
int
n)
{
int
i;
for
(i =
0
; i < n; i++) {
System.out.print(arr[i] +
" "
);
}
System.out.println(
""
);
}
// Driver program to test above functions
public
static
void
main(String[] args)
{
RearrangeArray arrange =
new
RearrangeArray();
int
arr[] = {
1
,
3
,
0
,
2
};
int
n = arr.length;
System.out.println(
"Given array is "
);
arrange.printArray(arr, n);
arrange.rearrangeNaive(arr, n);
System.out.println(
"Modified array is "
);
arrange.printArray(arr, n);
}
}
|
n
|
32.java
| 0.5 |
// java program to find the maximum sum
// such that no three are consecutive
import
java.io.*;
class
GFG {
// Returns maximum subsequence sum such that no three
// elements are consecutive
static
int
maxSumWO3Consec(
int
arr[],
int
n)
{
// Stores result for subarray arr[0..i], i.e.,
// maximum possible sum in subarray arr[0..i]
// such that no three elements are consecutive.
int
sum[] =
new
int
[n];
// Base cases (process first three elements)
if
(n >=
1
)
sum[
0
] = arr[
0
];
if
(n >=
2
)
sum[
1
] = arr[
0
] + arr[
1
];
if
(n >
2
)
sum[
2
] = Math.max(sum[
1
], Math.max(arr[
1
] + arr[
2
], arr[
0
] + arr[
2
]));
// Process rest of the elements
// We have three cases
// 1) Exclude arr[i], i.e., sum[i] = sum[i-1]
// 2) Exclude arr[i-1], i.e., sum[i] = sum[i-2] + arr[i]
// 3) Exclude arr[i-2], i.e., sum[i-3] + arr[i] + arr[i-1]
for
(
int
i =
3
; i < n; i++)
sum[i] = Math.max(Math.max(sum[i -
1
], sum[i -
2
] + arr[i]),
arr[i] + arr[i -
1
] + sum[i -
3
]);
return
sum[n -
1
];
}
// Driver code
public
static
void
main(String[] args)
{
int
arr[] = {
100
,
1000
,
100
,
1000
,
1
};
int
n = arr.length;
System.out.println(maxSumWO3Consec(arr, n));
}
}
// This code is contributed by vt_m
|
n
|
320.java
| 0.5 |
// Java program to find the maximum
// sum such that no three are
// consecutive using recursion.
import
java.util.Arrays;
class
GFG
{
static
int
arr[] = {
100
,
1000
,
100
,
1000
,
1
};
static
int
sum[] =
new
int
[
10000
];
// Returns maximum subsequence
// sum such that no three
// elements are consecutive
static
int
maxSumWO3Consec(
int
n)
{
if
(sum[n] != -
1
)
return
sum[n];
//Base cases (process first three elements)
if
(n ==
0
)
return
sum[n] =
0
;
if
(n ==
1
)
return
sum[n] = arr[
0
];
if
(n ==
2
)
return
sum[n] = arr[
1
] + arr[
0
];
// Process rest of the elements
// We have three cases
return
sum[n] = Math.max(Math.max(maxSumWO3Consec(n -
1
),
maxSumWO3Consec(n -
2
) + arr[n -
1
]),
arr[n -
2
] + arr[n -
1
] + maxSumWO3Consec(n -
3
));
}
// Driver code
public
static
void
main(String[] args)
{
int
n = arr.length;
Arrays.fill(sum, -
1
);
System.out.println(maxSumWO3Consec(n));
}
}
// This code is contributed by Rajput-Ji
|
n
|
321.java
| 0.5 |
// Java implementation to divide N into
// maximum number of segments
// of length a, b and c
import
java.util.*;
class
GFG
{
// function to find the maximum
// number of segments
static
int
maximumSegments(
int
n,
int
a,
int
b,
int
c)
{
// stores the maximum number of
// segments each index can have
int
dp[] =
new
int
[n +
10
];
// initialize with -1
Arrays.fill(dp, -
1
);
// 0th index will have 0 segments
// base case
dp[
0
] =
0
;
// traverse for all possible
// segments till n
for
(
int
i =
0
; i < n; i++)
{
if
(dp[i] != -
1
)
{
// conditions
if
(i + a <= n )
//avoid buffer overflow
dp[i + a] = Math.max(dp[i] +
1
,
dp[i + a]);
if
(i + b <= n )
//avoid buffer overflow
dp[i + b] = Math.max(dp[i] +
1
,
dp[i + b]);
if
(i + c <= n )
//avoid buffer overflow
dp[i + c] = Math.max(dp[i] +
1
,
dp[i + c]);
}
}
return
dp[n];
}
// Driver code
public
static
void
main(String arg[])
{
int
n =
7
, a =
5
, b =
2
, c =
5
;
System.out.print(maximumSegments(n, a, b, c));
}
}
// This code is contributed by Anant Agarwal.
|
n
|
329.java
| 0.5 |
// A space efficient Java program to rearrange contents of
// arr[] such that arr[j] becomes j if arr[i] is j
class
RearrangeArray {
// A utility function to rearrange elements in the cycle
// starting at arr[i]. This function assumes values in
// arr[] be from 1 to n. It changes arr[j-1] to i+1
// if arr[i-1] is j+1
void
rearrangeUtil(
int
arr[],
int
n,
int
i)
{
// 'val' is the value to be stored at 'arr[i]'
// The next value is determined using current index
int
val = -(i +
1
);
// The next index is determined
// using current value
i = arr[i] -
1
;
// While all elements in cycle are not processed
while
(arr[i] >
0
) {
// Store value at index as it is going to be
// used as next index
int
new_i = arr[i] -
1
;
// Update arr[]
arr[i] = val;
// Update value and index for next iteration
val = -(i +
1
);
i = new_i;
}
}
// A space efficient method to rearrange 'arr[0..n-1]'
// so that 'arr[j]' becomes 'i' if 'arr[i]' is 'j'
void
rearrange(
int
arr[],
int
n)
{
// Increment all values by 1, so that all elements
// can be made negative to mark them as visited
int
i;
for
(i =
0
; i < n; i++)
arr[i]++;
// Process all cycles
for
(i =
0
; i < n; i++) {
// Process cycle starting at arr[i] if this cycle is
// not already processed
if
(arr[i] >
0
)
rearrangeUtil(arr, n, i);
}
// Change sign and values of arr[] to get the original
// values back, i.e., values in range from 0 to n-1
for
(i =
0
; i < n; i++)
arr[i] = (-arr[i]) -
1
;
}
// A utility function to print contents of arr[0..n-1]
void
printArray(
int
arr[],
int
n)
{
int
i;
for
(i =
0
; i < n; i++)
System.out.print(arr[i] +
" "
);
System.out.println(
""
);
}
// Driver program
public
static
void
main(String[] args)
{
RearrangeArray arrange =
new
RearrangeArray();
int
arr[] = {
2
,
0
,
1
,
4
,
5
,
3
};
int
n = arr.length;
System.out.println(
"Given array is "
);
arrange.printArray(arr, n);
arrange.rearrange(arr, n);
System.out.println(
"Modified array is "
);
arrange.printArray(arr, n);
}
}
|
n
|
33.java
| 0.5 |
// A simple recursive JAVA program to find
// maximum sum by recursively breaking a
// number in 3 parts.
import
java.io.*;
class
GFG {
final
int
MAX =
1000000
;
// Function to find the maximum sum
static
int
breakSum(
int
n)
{
int
dp[] =
new
int
[n+
1
];
// base conditions
dp[
0
] =
0
; dp[
1
] =
1
;
// Fill in bottom-up manner using recursive
// formula.
for
(
int
i=
2
; i<=n; i++)
dp[i] = Math.max(dp[i/
2
] + dp[i/
3
] + dp[i/
4
], i);
return
dp[n];
}
// Driver program to test the above function
public
static
void
main (String[] args) {
int
n =
24
;
System.out.println(breakSum(n));
}
}
// This code is contributed by Amit Kumar
|
n
|
331.java
| 0.5 |
// Java Code for Maximum sum in a 2 x n grid
// such that no two elements are adjacent
import
java.util.*;
class
GFG {
// Function to find max sum without adjacent
public
static
int
maxSum(
int
grid[][],
int
n)
{
// Sum including maximum element of first
// column
int
incl = Math.max(grid[
0
][
0
], grid[
1
][
0
]);
// Not including first column's element
int
excl =
0
, excl_new;
// Traverse for further elements
for
(
int
i =
1
; i < n; i++ )
{
// Update max_sum on including or
// excluding of previous column
excl_new = Math.max(excl, incl);
// Include current column. Add maximum element
// from both row of current column
incl = excl + Math.max(grid[
0
][i], grid[
1
][i]);
// If current column doesn't to be included
excl = excl_new;
}
// Return maximum of excl and incl
// As that will be the maximum sum
return
Math.max(excl, incl);
}
/* Driver program to test above function */
public
static
void
main(String[] args)
{
int
grid[][] = {{
1
,
2
,
3
,
4
,
5
},
{
6
,
7
,
8
,
9
,
10
}};
int
n =
5
;
System.out.println(maxSum(grid, n));
}
}
// This code is contributed by Arnav Kr. Mandal.
|
n
|
333.java
| 0.5 |
// Java Program to find the length of
// substring with maximum difference of
// zeroes and ones in binary string.
import
java.util.*;
import
java.lang.*;
import
java.io.*;
class
GFG {
// Find the length of substring with maximum
// difference of zeros and ones in binary
// string
public
static
int
findLength(String str,
int
n)
{
int
current_sum =
0
;
int
max_sum =
0
;
// traverse a binary string from left to right
for
(
int
i =
0
; i < n; i++) {
// add current value to the current_sum
// according to the Character
// if it's '0' add 1 else -1
current_sum += (str.charAt(i) ==
'0'
?
1
: -
1
);
if
(current_sum <
0
)
current_sum =
0
;
// update maxium sum
max_sum = Math.max(current_sum, max_sum);
}
// return -1 if string does not contain any zero
// that means string contains all ones otherwise max_sum
return
max_sum ==
0
? -
1
: max_sum;
}
public
static
void
main(String[] args)
{
String str =
"11000010001"
;
int
n = str.length();
System.out.println(findLength(str, n));
}
}
|
n
|
334.java
| 0.5 |
// Java program to write characters in
// minimum time by inserting, removing
// and copying operation
public
class
GFG{
// method returns minimum time to write
// 'N' characters
static
int
minTimeForWritingChars(
int
N,
int
insert,
int
remove,
int
copy)
{
if
(N ==
0
)
return
0
;
if
(N ==
1
)
return
insert;
// declare dp array and initialize with zero
int
dp[] =
new
int
[N +
1
];
// loop for 'N' number of times
for
(
int
i =
1
; i <= N; i++)
{
/* if current char count is even then
choose minimum from result for (i-1)
chars and time for insertion and
result for half of chars and time
for copy */
if
(i %
2
==
0
)
dp[i] = Math.min(dp[i-
1
] + insert, dp[i/
2
] + copy);
/* if current char count is odd then
choose minimum from
result for (i-1) chars and time for
insertion and
result for half of chars and time for
copy and one extra character deletion*/
else
dp[i] = Math.min(dp[i-
1
] + insert,
dp[(i+
1
)/
2
] + copy + remove);
}
return
dp[N];
}
// Driver code to test above methods
public
static
void
main(String []args)
{
int
N =
9
;
int
insert =
1
, remove =
2
, copy =
1
;
System.out.println(minTimeForWritingChars(N, insert,remove, copy));
}
// This code is contributed by Ryuga
}
|
n
|
345.java
| 0.5 |
// Java program to print sum of all substring of
// a number represented as a string
import
java.util.Arrays;
class
GFG{
// Returns sum of all substring of num
public
static
int
sumOfSubstrings(String num)
{
int
n = num.length();
// allocate memory equal to length of string
int
sumofdigit[] =
new
int
[n];
// initialize first value with first digit
sumofdigit[
0
] = num.charAt(
0
)-
'0'
;
int
res = sumofdigit[
0
];
// loop over all digits of string
for
(
int
i =
1
; i < n; i++)
{
int
numi = num.charAt(i)-
'0'
;
// update each sumofdigit from previous value
sumofdigit[i] = (i+
1
) * numi +
10
* sumofdigit[i-
1
];
// add current value to the result
res += sumofdigit[i];
}
return
res;
}
// Driver code to test above methods
public
static
void
main(String[] args)
{
String num =
"1234"
;
System.out.println(sumOfSubstrings(num));
}
}
// This code is contributed by Arnav Kr. Mandal.
|
n
|
349.java
| 0.5 |
// Java program to find the maximum stolen value
import
java.io.*;
class
GFG
{
// Function to calculate the maximum stolen value
static
int
maxLoot(
int
hval[],
int
n)
{
if
(n ==
0
)
return
0
;
if
(n ==
1
)
return
hval[
0
];
if
(n ==
2
)
return
Math.max(hval[
0
], hval[
1
]);
// dp[i] represent the maximum value stolen
// so far after reaching house i.
int
[] dp =
new
int
[n];
// Initialize the dp[0] and dp[1]
dp[
0
] = hval[
0
];
dp[
1
] = Math.max(hval[
0
], hval[
1
]);
// Fill remaining positions
for
(
int
i =
2
; i<n; i++)
dp[i] = Math.max(hval[i]+dp[i-
2
], dp[i-
1
]);
return
dp[n-
1
];
}
// Driver program
public
static
void
main (String[] args)
{
int
hval[] = {
6
,
7
,
1
,
3
,
8
,
2
,
4
};
int
n = hval.length;
System.out.println(
"Maximum loot value : "
+ maxLoot(hval, n));
}
}
// Contributed by Pramod Kumar
|
n
|
350.java
| 0.5 |
// Java program to find the maximum stolen value
import
java.io.*;
class
GFG
{
// Function to calculate the maximum stolen value
static
int
maxLoot(
int
hval[],
int
n)
{
if
(n ==
0
)
return
0
;
int
value1 = hval[
0
];
if
(n ==
1
)
return
value1;
int
value2 = Math.max(hval[
0
], hval[
1
]);
if
(n ==
2
)
return
value2;
// contains maximum stolen value at the end
int
max_val =
0
;
// Fill remaining positions
for
(
int
i=
2
; i<n; i++)
{
max_val = Math.max(hval[i]+value1, value2);
value1 = value2;
value2 = max_val;
}
return
max_val;
}
// driver program
public
static
void
main (String[] args)
{
int
hval[] = {
6
,
7
,
1
,
3
,
8
,
2
,
4
};
int
n = hval.length;
System.out.println(
"Maximum loot value : "
+ maxLoot(hval, n));
}
}
// Contributed by Pramod kumar
|
n
|
351.java
| 0.5 |
// Java program to illustrate
// the number of ways to represent
// N as sum of 1, 3 and 4.
class
GFG {
// Function to count the
// number of ways to represent
// n as sum of 1, 3 and 4
static
int
countWays(
int
n)
{
int
DP[] =
new
int
[n +
1
];
// base cases
DP[
0
] = DP[
1
] = DP[
2
] =
1
;
DP[
3
] =
2
;
// iterate for all values from 4 to n
for
(
int
i =
4
; i <= n; i++)
DP[i] = DP[i -
1
] + DP[i -
3
]
+ DP[i -
4
];
return
DP[n];
}
// driver code
public
static
void
main(String[] args)
{
int
n =
10
;
System.out.println(countWays(n));
}
}
// This code is contributed
// by prerna saini.
|
n
|
352.java
| 0.5 |
// Java program to count ways to build street
// under given constraints
public
class
GFG {
// function to count ways of building
// a street of n rows
static
long
countWays(
int
n) {
long
dp[][] =
new
long
[
2
][n +
1
];
// base case
dp[
0
][
1
] =
1
;
dp[
1
][
1
] =
2
;
for
(
int
i =
2
; i <= n; i++) {
// ways of building houses in both
// the spots of ith row
dp[
0
][i] = dp[
0
][i -
1
] + dp[
1
][i -
1
];
// ways of building an office in one of
// the two spots of ith row
dp[
1
][i] = dp[
0
][i -
1
] *
2
+ dp[
1
][i -
1
];
}
// total ways for n rows
return
dp[
0
][n] + dp[
1
][n];
}
// driver program for checking above function
public
static
void
main(String[] args) {
int
n =
5
;
System.out.print(
"Total no of ways with n = "
+ n
+
" are: "
+ countWays(n));
}
}
/*This code is contributed by PrinciRaj1992*/
|
n
|
353.java
| 0.5 |
// Java implementation to count number
// of ways to tile a floor of size
// n x m using 1 x m tiles
import
java.io.*;
class
GFG {
// function to count the total number of ways
static
int
countWays(
int
n,
int
m)
{
// table to store values
// of subproblems
int
count[] =
new
int
[n +
1
];
count[
0
] =
0
;
// Fill the table upto value n
int
i;
for
(i =
1
; i <= n; i++) {
// recurrence relation
if
(i > m)
count[i] = count[i -
1
] + count[i - m];
// base cases
else
if
(i < m)
count[i] =
1
;
// i = = m
else
count[i] =
2
;
}
// required number of ways
return
count[n];
}
// Driver program
public
static
void
main(String[] args)
{
int
n =
7
;
int
m =
4
;
System.out.println(
"Number of ways = "
+ countWays(n, m));
}
}
// This code is contributed by vt_m.
|
n
|
354.java
| 0.5 |
// Java program to count of ways to place 1 x 4 tiles
// on n x 4 grid
import
java.io.*;
class
Grid
{
// Function that count the number of ways to place 1 x 4 tiles
// on n x 4 grid.
static
int
count(
int
n)
{
// Create a table to store results of sub-problems
// dp[i] stores count of ways for i x 4 grid.
int
[] dp =
new
int
[n+
1
];
dp[
0
] =
0
;
// Fill the table from d[1] to dp[n]
for
(
int
i=
1
;i<=n;i++)
{
// Base cases
if
(i >=
1
&& i <=
3
)
dp[i] =
1
;
else
if
(i==
4
)
dp[i] =
2
;
else
{
// dp(i-1) : Place first tile horizontally
// dp(i-4) : Place first tile vertically
// which means 3 more tiles have
// to be placed vertically.
dp[i] = dp[i-
1
] + dp[i-
4
];
}
}
return
dp[n];
}
// Driver program
public
static
void
main (String[] args)
{
int
n =
5
;
System.out.println(
"Count of ways is: "
+ count(n));
}
}
// Contributed by Pramod Kumar
|
n
|
355.java
| 0.5 |
// Java program for counting n digit numbers with
// non decreasing digits
import
java.io.*;
class
GFG {
// Function that returns count of non- decreasing numbers
// with n digits
static
int
nonDecNums(
int
n)
{
// a[i][j] = count of all possible number
// with i digits having leading digit as j
int
[][] a =
new
int
[n +
1
][
10
];
// Initialization of all 0-digit number
for
(
int
i =
0
; i <=
9
; i++)
a[
0
][i] =
1
;
// Initialization of all i-digit
// non-decreasing number leading with 9
for
(
int
i =
1
; i <= n; i++)
a[i][
9
] =
1
;
// for all digits we should calculate
// number of ways depending upon leading
// digits
for
(
int
i =
1
; i <= n; i++)
for
(
int
j =
8
; j >=
0
; j--)
a[i][j] = a[i -
1
][j] + a[i][j +
1
];
return
a[n][
0
];
}
// driver program
public
static
void
main(String[] args)
{
int
n =
2
;
System.out.println(
"Non-decreasing digits = "
+ nonDecNums(n));
}
}
// Contributed by Pramod Kumar
|
n
|
356.java
| 0.5 |
// Java program to find maximum revenue
// by placing billboard on the highway
// with given constarints.
class
GFG
{
static
int
maxRevenue(
int
m,
int
[] x,
int
[] revenue,
int
n,
int
t)
{
// Array to store maximum revenue
// at each miles.
int
[] maxRev =
new
int
[m +
1
];
for
(
int
i =
0
; i < m +
1
; i++)
maxRev[i] =
0
;
// actual minimum distance between
// 2 billboards.
int
nxtbb =
0
;
for
(
int
i =
1
; i <= m; i++)
{
// check if all billboards are
// already placed.
if
(nxtbb < n)
{
// check if we have billboard for
// that particular mile. If not,
// copy the previous maximum revenue.
if
(x[nxtbb] != i)
maxRev[i] = maxRev[i -
1
];
// we do have billboard for this mile.
else
{
// We have 2 options, we either take
// current or we ignore current billboard.
// If current position is less than or
// equal to t, then we can have only
// one billboard.
if
(i <= t)
maxRev[i] = Math.max(maxRev[i -
1
],
revenue[nxtbb]);
// Else we may have to remove
// previously placed billboard
else
maxRev[i] = Math.max(maxRev[i - t -
1
] +
revenue[nxtbb],
maxRev[i -
1
]);
nxtbb++;
}
}
else
maxRev[i] = maxRev[i -
1
];
}
return
maxRev[m];
}
// Driver Code
public
static
void
main(String []args)
{
int
m =
20
;
int
[] x =
new
int
[]{
6
,
7
,
12
,
13
,
14
};
int
[] revenue =
new
int
[]{
5
,
6
,
5
,
3
,
1
};
int
n = x.length;
int
t =
5
;
System.out.println(maxRevenue(m, x, revenue, n, t));
}
}
// This code is contributed by Ita_c.
|
n
|
358.java
| 0.5 |
// Java program to rearrange an
// array in minimum maximum form
public
class
Main {
// Prints max at first position, min at second
// position second max at third position, second
// min at fourth position and so on.
public
static
void
rearrange(
int
arr[],
int
n)
{
// initialize index of first minimum and first
// maximum element
int
max_ele = arr[n -
1
];
int
min_ele = arr[
0
];
// traverse array elements
for
(
int
i =
0
; i < n; i++) {
// at even index : we have to put maximum element
if
(i %
2
==
0
) {
arr[i] = max_ele;
max_ele -=
1
;
}
// at odd index : we have to put minimum element
else
{
arr[i] = min_ele;
min_ele +=
1
;
}
}
}
// Driver code
public
static
void
main(String args[])
{
int
arr[] = {
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
};
int
n = arr.length;
System.out.println(
"Original Array"
);
for
(
int
i =
0
; i < n; i++)
System.out.print(arr[i] +
" "
);
rearrange(arr, n);
System.out.print(
"\nModified Array\n"
);
for
(
int
i =
0
; i < n; i++)
System.out.print(arr[i] +
" "
);
}
}
|
n
|
36.java
| 0.5 |
// Java program for calculating LISS
// using dynamic programming
public
class
LisTree
{
/* A binary tree node has data, pointer
to left child and a pointer to right
child */
static
class
node
{
int
data, liss;
node left, right;
public
node(
int
data)
{
this
.data = data;
this
.liss =
0
;
}
}
// A memoization function returns size
// of the largest independent set in
// a given binary tree
static
int
liss(node root)
{
if
(root ==
null
)
return
0
;
if
(root.liss !=
0
)
return
root.liss;
if
(root.left ==
null
&& root.right ==
null
)
return
root.liss =
1
;
// Calculate size excluding the
// current node
int
liss_excl = liss(root.left) + liss(root.right);
// Calculate size including the
// current node
int
liss_incl =
1
;
if
(root.left !=
null
)
{
liss_incl += (liss(root.left.left) + liss(root.left.right));
}
if
(root.right !=
null
)
{
liss_incl += (liss(root.right.left) + liss(root.right.right));
}
// Maximum of two sizes is LISS,
// store it for future uses.
return
root.liss = Math.max(liss_excl, liss_incl);
}
public
static
void
main(String[] args)
{
// Let us construct the tree given
// in the above diagram
node root =
new
node(
20
);
root.left =
new
node(
8
);
root.left.left =
new
node(
4
);
root.left.right =
new
node(
12
);
root.left.right.left =
new
node(
10
);
root.left.right.right =
new
node(
14
);
root.right =
new
node(
22
);
root.right.right =
new
node(
25
);
System.out.println(
"Size of the Largest Independent Set is "
+ liss(root));
}
}
// This code is contributed by Rishabh Mahrsee
|
n
|
360.java
| 0.5 |
// A dynamic programming based Java program for partition problem
import
java.io.*;
class
Partition {
// Returns true if arr[] can be partitioned in two subsets of
// equal sum, otherwise false
static
boolean
findPartition (
int
arr[],
int
n)
{
int
sum =
0
;
int
i, j;
// Caculcate sun of all elements
for
(i =
0
; i < n; i++)
sum += arr[i];
if
(sum%
2
!=
0
)
return
false
;
boolean
part[][]=
new
boolean
[sum/
2
+
1
][n+
1
];
// initialize top row as true
for
(i =
0
; i <= n; i++)
part[
0
][i] =
true
;
// initialize leftmost column, except part[0][0], as 0
for
(i =
1
; i <= sum/
2
; i++)
part[i][
0
] =
false
;
// Fill the partition table in botton up manner
for
(i =
1
; i <= sum/
2
; i++)
{
for
(j =
1
; j <= n; j++)
{
part[i][j] = part[i][j-
1
];
if
(i >= arr[j-
1
])
part[i][j] = part[i][j] ||
part[i - arr[j-
1
]][j-
1
];
}
}
/* // uncomment this part to print table
for (i = 0; i <= sum/2; i++)
{
for (j = 0; j <= n; j++)
printf ("%4d", part[i][j]);
printf("\n");
} */
return
part[sum/
2
][n];
}
/*Driver function to check for above function*/
public
static
void
main (String[] args)
{
int
arr[] = {
3
,
1
,
1
,
2
,
2
,
1
};
int
n = arr.length;
if
(findPartition(arr, n) ==
true
)
System.out.println(
"Can be divided into two "
"subsets of equal sum"
);
else
System.out.println(
"Can not be divided into"
" two subsets of equal sum"
);
}
}
/* This code is contributed by Devesh Agrawal */
|
n
|
362.java
| 0.5 |
// A DP based Java program to find maximum tasks.
class
GFG
{
// Returns the maximum among the 2 numbers
static
int
max(
int
x,
int
y)
{
return
(x > y ? x : y);
}
// Returns maximum amount of task that can be
// done till day n
static
int
maxTasks(
int
[]high,
int
[]low,
int
n)
{
// An array task_dp that stores the maximum
// task done
int
[] task_dp =
new
int
[n +
1
];
// If n = 0, no solution exists
task_dp[
0
] =
0
;
// If n = 1, high effort task on that day will
// be the solution
task_dp[
1
] = high[
0
];
// Fill the entire array determining which
// task to choose on day i
for
(
int
i =
2
; i <= n; i++)
task_dp[i] = Math.max(high[i -
1
] + task_dp[i -
2
],
low[i -
1
] + task_dp[i -
1
]);
return
task_dp[n];
}
// Driver code
public
static
void
main(String[] args)
{
int
n =
5
;
int
[]high = {
3
,
6
,
8
,
7
,
6
};
int
[]low = {
1
,
5
,
4
,
5
,
3
};
System.out.println(maxTasks(high, low, n));
}
}
// This code is contributed by Code_Mech.
|
n
|
365.java
| 0.5 |
// Java program to Move All -ve Element At End
// Without changing order Of Array Element
import
java.util.Arrays;
class
GFG {
// Moves all -ve element to end of array in
// same order.
static
void
segregateElements(
int
arr[],
int
n)
{
// Create an empty array to store result
int
temp[] =
new
int
[n];
// Traversal array and store +ve element in
// temp array
int
j =
0
;
// index of temp
for
(
int
i =
0
; i < n; i++)
if
(arr[i] >=
0
)
temp[j++] = arr[i];
// If array contains all positive or all
// negative.
if
(j == n || j ==
0
)
return
;
// Store -ve element in temp array
for
(
int
i =
0
; i < n; i++)
if
(arr[i] <
0
)
temp[j++] = arr[i];
// Copy contents of temp[] to arr[]
for
(
int
i =
0
; i < n; i++)
arr[i] = temp[i];
}
// Driver code
public
static
void
main(String arg[])
{
int
arr[] = {
1
, -
1
, -
3
, -
2
,
7
,
5
,
11
,
6
};
int
n = arr.length;
segregateElements(arr, n);
for
(
int
i =
0
; i < n; i++)
System.out.print(arr[i] +
" "
);
}
}
// This code is contributed by Anant Agarwal.
|
n
|
37.java
| 0.5 |
// Java program for different tree traversals
/* Class containing left and right child of current
node and key value*/
class
Node
{
int
key;
Node left, right;
public
Node(
int
item)
{
key = item;
left = right =
null
;
}
}
class
BinaryTree
{
// Root of Binary Tree
Node root;
BinaryTree()
{
root =
null
;
}
/* Given a binary tree, print its nodes according to the
"bottom-up" postorder traversal. */
void
printPostorder(Node node)
{
if
(node ==
null
)
return
;
// first recur on left subtree
printPostorder(node.left);
// then recur on right subtree
printPostorder(node.right);
// now deal with the node
System.out.print(node.key +
" "
);
}
/* Given a binary tree, print its nodes in inorder*/
void
printInorder(Node node)
{
if
(node ==
null
)
return
;
/* first recur on left child */
printInorder(node.left);
/* then print the data of node */
System.out.print(node.key +
" "
);
/* now recur on right child */
printInorder(node.right);
}
/* Given a binary tree, print its nodes in preorder*/
void
printPreorder(Node node)
{
if
(node ==
null
)
return
;
/* first print data of node */
System.out.print(node.key +
" "
);
/* then recur on left sutree */
printPreorder(node.left);
/* now recur on right subtree */
printPreorder(node.right);
}
// Wrappers over above recursive functions
void
printPostorder() { printPostorder(root); }
void
printInorder() { printInorder(root); }
void
printPreorder() { printPreorder(root); }
// Driver method
public
static
void
main(String[] args)
{
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(
1
);
tree.root.left =
new
Node(
2
);
tree.root.right =
new
Node(
3
);
tree.root.left.left =
new
Node(
4
);
tree.root.left.right =
new
Node(
5
);
System.out.println(
"Preorder traversal of binary tree is "
);
tree.printPreorder();
System.out.println(
"\nInorder traversal of binary tree is "
);
tree.printInorder();
System.out.println(
"\nPostorder traversal of binary tree is "
);
tree.printPostorder();
}
}
|
n
|
374.java
| 0.5 |
// Java program for finding postorder
// traversal of BST from preorder traversal
import
java.util.* ;
class
Solution
{
static
class
INT
{
int
data;
INT(
int
d)
{
data=d;
}
}
// Function to find postorder traversal from
// preorder traversal.
static
void
findPostOrderUtil(
int
pre[],
int
n,
int
minval,
int
maxval, INT preIndex)
{
// If entire preorder array is traversed then
// return as no more element is left to be
// added to post order array.
if
(preIndex.data == n)
return
;
// If array element does not lie in range specified,
// then it is not part of current subtree.
if
(pre[preIndex.data] < minval || pre[preIndex.data] > maxval) {
return
;
}
// Store current value, to be printed later, after
// printing left and right subtrees. Increment
// preIndex to find left and right subtrees,
// and pass this updated value to recursive calls.
int
val = pre[preIndex.data];
preIndex.data++;
// All elements with value between minval and val
// lie in left subtree.
findPostOrderUtil(pre, n, minval, val, preIndex);
// All elements with value between val and maxval
// lie in right subtree.
findPostOrderUtil(pre, n, val, maxval, preIndex);
System.out.print( val +
" "
);
}
// Function to find postorder traversal.
static
void
findPostOrder(
int
pre[],
int
n)
{
// To store index of element to be
// traversed next in preorder array.
// This is passed by reference to
// utility function.
INT preIndex =
new
INT(
0
);
findPostOrderUtil(pre, n, Integer.MIN_VALUE,
Integer.MAX_VALUE, preIndex);
}
// Driver code
public
static
void
main(String args[])
{
int
pre[] = {
40
,
30
,
35
,
80
,
100
};
int
n = pre.length;
// Calling function
findPostOrder(pre, n);
}
}
// This code is contributed
// by Arnab Kundu
|
n
|
377.java
| 0.5 |
// Java implementation to replace each node
// in binary tree with the sum of its inorder
// predecessor and successor
import
java.util.*;
class
Solution
{
// node of a binary tree
static
class
Node {
int
data;
Node left, right;
}
//INT class
static
class
INT
{
int
data;
}
// function to get a new node of a binary tree
static
Node getNode(
int
data)
{
// allocate node
Node new_node =
new
Node();
// put in the data;
new_node.data = data;
new_node.left = new_node.right =
null
;
return
new_node;
}
// function to store the inorder traversal
// of the binary tree in 'arr'
static
void
storeInorderTraversal( Node root,
Vector<Integer> arr)
{
// if root is null
if
(root==
null
)
return
;
// first recur on left child
storeInorderTraversal(root.left, arr);
// then store the root's data in 'arr'
arr.add(root.data);
// now recur on right child
storeInorderTraversal(root.right, arr);
}
// function to replace each node with the sum of its
// inorder predecessor and successor
static
void
replaceNodeWithSum( Node root,
Vector<Integer> arr, INT i)
{
// if root is null
if
(root==
null
)
return
;
// first recur on left child
replaceNodeWithSum(root.left, arr, i);
// replace node's data with the sum of its
// inorder predecessor and successor
root.data = arr.get(i.data -
1
) + arr.get(i.data +
1
);
// move 'i' to point to the next 'arr' element
i.data++;
// now recur on right child
replaceNodeWithSum(root.right, arr, i);
}
// Utility function to replace each node in binary
// tree with the sum of its inorder predecessor
// and successor
static
void
replaceNodeWithSumUtil( Node root)
{
// if tree is empty
if
(root==
null
)
return
;
Vector<Integer> arr=
new
Vector<Integer>();
// store the value of inorder predecessor
// for the leftmost leaf
arr.add(
0
);
// store the inoder traversal of the tree in 'arr'
storeInorderTraversal(root, arr);
// store the value of inorder successor
// for the rightmost leaf
arr.add(
0
);
// replace each node with the required sum
INT i =
new
INT();
i.data=
1
;
replaceNodeWithSum(root, arr, i);
}
// function to print the preorder traversal
// of a binary tree
static
void
preorderTraversal( Node root)
{
// if root is null
if
(root==
null
)
return
;
// first print the data of node
System.out.print( root.data +
" "
);
// then recur on left subtree
preorderTraversal(root.left);
// now recur on right subtree
preorderTraversal(root.right);
}
// Driver program to test above
public
static
void
main(String args[])
{
// binary tree formation
Node root = getNode(
1
);
// 1
root.left = getNode(
2
);
// / \
root.right = getNode(
3
);
// 2 3
root.left.left = getNode(
4
);
// / \ / \
root.left.right = getNode(
5
);
// 4 5 6 7
root.right.left = getNode(
6
);
root.right.right = getNode(
7
);
System.out.println(
"Preorder Traversal before tree modification:"
);
preorderTraversal(root);
replaceNodeWithSumUtil(root);
System.out.println(
"\nPreorder Traversal after tree modification:"
);
preorderTraversal(root);
}
}
//contributed by Arnab Kundu
|
n
|
378.java
| 0.5 |
// Java code to rearrange an array such
// that even index elements are smaller
// and odd index elements are greater
// than their next.
class
GFG {
static
void
rearrange(
int
arr[],
int
n)
{
int
temp;
for
(
int
i =
0
; i < n -
1
; i++) {
if
(i %
2
==
0
&& arr[i] > arr[i +
1
]) {
temp = arr[i];
arr[i] = arr[i +
1
];
arr[i +
1
] = temp;
}
if
(i %
2
!=
0
&& arr[i] < arr[i +
1
]) {
temp = arr[i];
arr[i] = arr[i +
1
];
arr[i +
1
] = temp;
}
}
}
/* Utility that prints out an array in
a line */
static
void
printArray(
int
arr[],
int
size)
{
for
(
int
i =
0
; i < size; i++)
System.out.print(arr[i] +
" "
);
System.out.println();
}
// Driver code
public
static
void
main(String[] args)
{
int
arr[] = {
6
,
4
,
2
,
1
,
8
,
3
};
int
n = arr.length;
System.out.print(
"Before rearranging: \n"
);
printArray(arr, n);
rearrange(arr, n);
System.out.print(
"After rearranging: \n"
);
printArray(arr, n);
}
}
// This code is contributed by Anant Agarwal.
|
n
|
38.java
| 0.5 |
// Java program to find inorder successor of a node
class
Solution
{
// A Binary Tree Node
static
class
Node
{
int
data;
Node left, right;
}
// Temporary node for case 2
static
Node temp =
new
Node();
// Utility function to create a new tree node
static
Node newNode(
int
data)
{
Node temp =
new
Node();
temp.data = data;
temp.left = temp.right =
null
;
return
temp;
}
// function to find left most node in a tree
static
Node leftMostNode(Node node)
{
while
(node !=
null
&& node.left !=
null
)
node = node.left;
return
node;
}
// function to find right most node in a tree
static
Node rightMostNode(Node node)
{
while
(node !=
null
&& node.right !=
null
)
node = node.right;
return
node;
}
// recursive function to find the Inorder Scuccessor
// when the right child of node x is null
static
Node findInorderRecursive(Node root, Node x )
{
if
(root==
null
)
return
null
;
if
(root==x || (temp = findInorderRecursive(root.left,x))!=
null
||
(temp = findInorderRecursive(root.right,x))!=
null
)
{
if
(temp!=
null
)
{
if
(root.left == temp)
{
System.out.print(
"Inorder Successor of "
+x.data);
System.out.print(
" is "
+ root.data +
"\n"
);
return
null
;
}
}
return
root;
}
return
null
;
}
// function to find inorder successor of
// a node
static
void
inorderSuccesor(Node root, Node x)
{
// Case1: If right child is not null
if
(x.right !=
null
)
{
Node inorderSucc = leftMostNode(x.right);
System.out.print(
"Inorder Successor of "
+x.data+
" is "
);
System.out.print(inorderSucc.data+
"\n"
);
}
// Case2: If right child is null
if
(x.right ==
null
)
{
int
f =
0
;
Node rightMost = rightMostNode(root);
// case3: If x is the right most node
if
(rightMost == x)
System.out.print(
"No inorder successor! Right most node.\n"
);
else
findInorderRecursive(root, x);
}
}
// Driver program to test above functions
public
static
void
main(String args[])
{
// Let's con the binary tree
// as shown in above diagram
Node root = newNode(
1
);
root.left = newNode(
2
);
root.right = newNode(
3
);
root.left.left = newNode(
4
);
root.left.right = newNode(
5
);
root.right.right = newNode(
6
);
// Case 1
inorderSuccesor(root, root.right);
// case 2
inorderSuccesor(root, root.left.left);
// case 3
inorderSuccesor(root, root.right.right);
}
}
//contributed by Arnab Kundu
|
n
|
381.java
| 0.5 |
// Java program for nth nodes of inorder traversals
import
java.util. *;
class
Solution
{
static
int
count =
0
;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
static
class
Node {
int
data;
Node left;
Node right;
}
/* Helper function that allocates a new node with the
given data and null left and right pointers. */
static
Node newNode(
int
data)
{
Node node =
new
Node();
node.data = data;
node.left =
null
;
node.right =
null
;
return
(node);
}
/* Given a binary tree, print its nth nodes of inorder*/
static
void
NthInorder( Node node,
int
n)
{
if
(node ==
null
)
return
;
if
(count <= n) {
/* first recur on left child */
NthInorder(node.left, n);
count++;
// when count = n then print element
if
(count == n)
System.out.printf(
"%d "
, node.data);
/* now recur on right child */
NthInorder(node.right, n);
}
}
/* Driver program to test above functions*/
public
static
void
main(String args[])
{
Node root = newNode(
10
);
root.left = newNode(
20
);
root.right = newNode(
30
);
root.left.left = newNode(
40
);
root.left.right = newNode(
50
);
int
n =
4
;
NthInorder(root, n);
}
}
// This code is contributed
// by Arnab Kundu
|
n
|
382.java
| 0.5 |
// Java program to find n-th node of
// Postorder Traversal of Binary Tree
public
class
NthNodePostOrder {
static
int
flag =
0
;
// function to find the N-th node in the postorder
// traversal of a given binary tree
public
static
void
NthPostordernode(Node root,
int
N)
{
if
(root ==
null
)
return
;
if
(flag <= N)
{
// left recursion
NthPostordernode(root.left, N);
// right recursion
NthPostordernode(root.right, N);
flag++;
// prints the n-th node of preorder traversal
if
(flag == N)
System.out.print(root.data);
}
}
public
static
void
main(String args[]) {
Node root =
new
Node(
25
);
root.left =
new
Node(
20
);
root.right =
new
Node(
30
);
root.left.left =
new
Node(
18
);
root.left.right =
new
Node(
22
);
root.right.left =
new
Node(
24
);
root.right.right =
new
Node(
32
);
int
N =
6
;
// prints n-th node found
NthPostordernode(root, N);
}
}
/* A binary tree node structure */
class
Node
{
int
data;
Node left, right;
Node(
int
data)
{
this
.data=data;
}
};
// This code is contributed by Gaurav Tiwari
|
n
|
383.java
| 0.5 |
// Java implementation of an O(n) approach of level order
// traversal in spiral form
import
java.util.*;
// A Binary Tree node
class
Node {
int
data;
Node left, right;
public
Node(
int
item)
{
data = item;
left = right =
null
;
}
}
class
BinaryTree {
static
Node root;
void
printSpiral(Node node)
{
if
(node ==
null
)
return
;
// NULL check
// Create two stacks to store alternate levels
// For levels to be printed from right to left
Stack<Node> s1 =
new
Stack<Node>();
// For levels to be printed from left to right
Stack<Node> s2 =
new
Stack<Node>();
// Push first level to first stack 's1'
s1.push(node);
// Keep printing while any of the stacks has some nodes
while
(!s1.empty() || !s2.empty()) {
// Print nodes of current level from s1 and push nodes of
// next level to s2
while
(!s1.empty()) {
Node temp = s1.peek();
s1.pop();
System.out.print(temp.data +
" "
);
// Note that is right is pushed before left
if
(temp.right !=
null
)
s2.push(temp.right);
if
(temp.left !=
null
)
s2.push(temp.left);
}
// Print nodes of current level from s2 and push nodes of
// next level to s1
while
(!s2.empty()) {
Node temp = s2.peek();
s2.pop();
System.out.print(temp.data +
" "
);
// Note that is left is pushed before right
if
(temp.left !=
null
)
s1.push(temp.left);
if
(temp.right !=
null
)
s1.push(temp.right);
}
}
}
public
static
void
main(String[] args)
{
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(
1
);
tree.root.left =
new
Node(
2
);
tree.root.right =
new
Node(
3
);
tree.root.left.left =
new
Node(
7
);
tree.root.left.right =
new
Node(
6
);
tree.root.right.left =
new
Node(
5
);
tree.root.right.right =
new
Node(
4
);
System.out.println(
"Spiral Order traversal of Binary Tree is "
);
tree.printSpiral(root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
|
n
|
385.java
| 0.5 |
// Java program to do level order
// traversal line by line
import
java.util.LinkedList;
import
java.util.Queue;
public
class
GFG {
static
class
Node {
int
data;
Node left;
Node right;
Node(
int
data) {
this
.data = data;
left =
null
;
right =
null
;
}
}
// Prints level order traversal line
// by line using two queues.
static
void
levelOrder(Node root) {
if
(root ==
null
)
return
;
Queue<Node> q =
new
LinkedList<>();
// Pushing root node into the queue.
q.add(root);
// Pushing delimiter into the queue.
q.add(
null
);
// Executing loop till queue becomes
// empty
while
(!q.isEmpty()) {
Node curr = q.poll();
// condition to check the
// occurence of next level
if
(curr ==
null
) {
if
(!q.isEmpty()) {
q.add(
null
);
System.out.println();
}
}
else
{
// Pushing left child current node
if
(curr.left !=
null
)
q.add(curr.left);
// Pushing right child current node
if
(curr.right !=
null
)
q.add(curr.right);
System.out.print(curr.data +
" "
);
}
}
}
// Driver function
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.right =
new
Node(
6
);
levelOrder(root);
}
}
// This code is Contributed by Rishabh Jindal
|
n
|
386.java
| 0.5 |
// A recursive java program to print reverse level order traversal
// using stack and queue
import
java.util.LinkedList;
import
java.util.Queue;
import
java.util.Stack;
/* A binary tree node has data, pointer to left and right children */
class
Node
{
int
data;
Node left, right;
Node(
int
item)
{
data = item;
left = right;
}
}
class
BinaryTree
{
Node root;
/* Given a binary tree, print its nodes in reverse level order */
void
reverseLevelOrder(Node node)
{
Stack<Node> S =
new
Stack();
Queue<Node> Q =
new
LinkedList();
Q.add(node);
// Do something like normal level order traversal order.Following
// are the differences with normal level order traversal
// 1) Instead of printing a node, we push the node to stack
// 2) Right subtree is visited before left subtree
while
(Q.isEmpty() ==
false
)
{
/* Dequeue node and make it root */
node = Q.peek();
Q.remove();
S.push(node);
/* Enqueue right child */
if
(node.right !=
null
)
// NOTE: RIGHT CHILD IS ENQUEUED BEFORE LEFT
Q.add(node.right);
/* Enqueue left child */
if
(node.left !=
null
)
Q.add(node.left);
}
// Now pop all items from stack one by one and print them
while
(S.empty() ==
false
)
{
node = S.peek();
System.out.print(node.data +
" "
);
S.pop();
}
}
// Driver program to test above functions
public
static
void
main(String args[])
{
BinaryTree tree =
new
BinaryTree();
// Let us create trees shown in above diagram
tree.root =
new
Node(
1
);
tree.root.left =
new
Node(
2
);
tree.root.right =
new
Node(
3
);
tree.root.left.left =
new
Node(
4
);
tree.root.left.right =
new
Node(
5
);
tree.root.right.left =
new
Node(
6
);
tree.root.right.right =
new
Node(
7
);
System.out.println(
"Level Order traversal of binary tree is :"
);
tree.reverseLevelOrder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal
|
n
|
388.java
| 0.5 |
// Java program for special level order traversal
import
java.util.LinkedList;
import
java.util.Queue;
/* Class containing left and right child of current
node and key value*/
class
Node
{
int
data;
Node left, right;
public
Node(
int
item)
{
data = item;
left = right =
null
;
}
}
class
BinaryTree
{
Node root;
/* Given a perfect binary tree, print its nodes in specific
level order */
void
printSpecificLevelOrder(Node node)
{
if
(node ==
null
)
return
;
// Let us print root and next level first
System.out.print(node.data);
// Since it is perfect Binary Tree, right is not checked
if
(node.left !=
null
)
System.out.print(
" "
+ node.left.data +
" "
+ node.right.data);
// Do anything more if there are nodes at next level in
// given perfect Binary Tree
if
(node.left.left ==
null
)
return
;
// Create a queue and enqueue left and right children of root
Queue<Node> q =
new
LinkedList<Node>();
q.add(node.left);
q.add(node.right);
// We process two nodes at a time, so we need two variables
// to store two front items of queue
Node first =
null
, second =
null
;
// traversal loop
while
(!q.isEmpty())
{
// Pop two items from queue
first = q.peek();
q.remove();
second = q.peek();
q.remove();
// Print children of first and second in reverse order
System.out.print(
" "
+ first.left.data +
" "
+second.right.data);
System.out.print(
" "
+ first.right.data +
" "
+second.left.data);
// If first and second have grandchildren, enqueue them
// in reverse order
if
(first.left.left !=
null
)
{
q.add(first.left);
q.add(second.right);
q.add(first.right);
q.add(second.left);
}
}
}
// Driver program to test for above functions
public
static
void
main(String args[])
{
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(
1
);
tree.root.left =
new
Node(
2
);
tree.root.right =
new
Node(
3
);
tree.root.left.left =
new
Node(
4
);
tree.root.left.right =
new
Node(
5
);
tree.root.right.left =
new
Node(
6
);
tree.root.right.right =
new
Node(
7
);
tree.root.left.left.left =
new
Node(
8
);
tree.root.left.left.right =
new
Node(
9
);
tree.root.left.right.left =
new
Node(
10
);
tree.root.left.right.right =
new
Node(
11
);
tree.root.right.left.left =
new
Node(
12
);
tree.root.right.left.right =
new
Node(
13
);
tree.root.right.right.left =
new
Node(
14
);
tree.root.right.right.right =
new
Node(
15
);
tree.root.left.left.left.left =
new
Node(
16
);
tree.root.left.left.left.right =
new
Node(
17
);
tree.root.left.left.right.left =
new
Node(
18
);
tree.root.left.left.right.right =
new
Node(
19
);
tree.root.left.right.left.left =
new
Node(
20
);
tree.root.left.right.left.right =
new
Node(
21
);
tree.root.left.right.right.left =
new
Node(
22
);
tree.root.left.right.right.right =
new
Node(
23
);
tree.root.right.left.left.left =
new
Node(
24
);
tree.root.right.left.left.right =
new
Node(
25
);
tree.root.right.left.right.left =
new
Node(
26
);
tree.root.right.left.right.right =
new
Node(
27
);
tree.root.right.right.left.left =
new
Node(
28
);
tree.root.right.right.left.right =
new
Node(
29
);
tree.root.right.right.right.left =
new
Node(
30
);
tree.root.right.right.right.right =
new
Node(
31
);
System.out.println(
"Specific Level Order traversal of binary"
+
"tree is "
);
tree.printSpecificLevelOrder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal
|
n
|
389.java
| 0.5 |
// Java program to update every array element with
// multiplication of previous and next numbers in array
import
java.io.*;
import
java.util.*;
import
java.lang.Math;
class
Multipy
{
static
void
modify(
int
arr[],
int
n)
{
// Nothing to do when array size is 1
if
(n <=
1
)
return
;
// store current value of arr[0] and update it
int
prev = arr[
0
];
arr[
0
] = arr[
0
] * arr[
1
];
// Update rest of the array elements
for
(
int
i=
1
; i<n-
1
; i++)
{
// Store current value of next interation
int
curr = arr[i];
// Update current value using previos value
arr[i] = prev * arr[i+
1
];
// Update previous value
prev = curr;
}
// Update last array element
arr[n-
1
] = prev * arr[n-
1
];
}
// Driver program to test above function
public
static
void
main(String[] args)
{
int
arr[] = {
2
,
3
,
4
,
5
,
6
};
int
n = arr.length;
modify(arr, n);
for
(
int
i=
0
; i<n; i++)
System.out.print(arr[i]+
" "
);
}
}
/* This code is contributed by Devesh Agrawal */
|
n
|
39.java
| 0.5 |
// Java program to reverse alternate levels of perfect binary tree
// A binary tree node
class
Node {
char
data;
Node left, right;
Node(
char
item) {
data = item;
left = right =
null
;
}
}
// class to access index value by reference
class
Index {
int
index;
}
class
BinaryTree {
Node root;
Index index_obj =
new
Index();
// function to store alternate levels in a tree
void
storeAlternate(Node node,
char
arr[], Index index,
int
l) {
// base case
if
(node ==
null
) {
return
;
}
// store elements of left subtree
storeAlternate(node.left, arr, index, l +
1
);
// store this node only if level is odd
if
(l %
2
!=
0
) {
arr[index.index] = node.data;
index.index++;
}
storeAlternate(node.right, arr, index, l +
1
);
}
// Function to modify Binary Tree (All odd level nodes are
// updated by taking elements from array in inorder fashion)
void
modifyTree(Node node,
char
arr[], Index index,
int
l) {
// Base case
if
(node ==
null
) {
return
;
}
// Update nodes in left subtree
modifyTree(node.left, arr, index, l +
1
);
// Update this node only if this is an odd level node
if
(l %
2
!=
0
) {
node.data = arr[index.index];
(index.index)++;
}
// Update nodes in right subtree
modifyTree(node.right, arr, index, l +
1
);
}
// A utility function to reverse an array from index
// 0 to n-1
void
reverse(
char
arr[],
int
n) {
int
l =
0
, r = n -
1
;
while
(l < r) {
char
temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
void
reverseAlternate() {
reverseAlternate(root);
}
// The main function to reverse alternate nodes of a binary tree
void
reverseAlternate(Node node) {
// Create an auxiliary array to store nodes of alternate levels
char
[] arr =
new
char
[
100
];
// First store nodes of alternate levels
storeAlternate(node, arr, index_obj,
0
);
//index_obj.index = 0;
// Reverse the array
reverse(arr, index_obj.index);
// Update tree by taking elements from array
index_obj.index =
0
;
modifyTree(node, arr, index_obj,
0
);
}
void
printInorder() {
printInorder(root);
}
// A utility function to print indorder traversal of a
// 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(
'a'
);
tree.root.left =
new
Node(
'b'
);
tree.root.right =
new
Node(
'c'
);
tree.root.left.left =
new
Node(
'd'
);
tree.root.left.right =
new
Node(
'e'
);
tree.root.right.left =
new
Node(
'f'
);
tree.root.right.right =
new
Node(
'g'
);
tree.root.left.left.left =
new
Node(
'h'
);
tree.root.left.left.right =
new
Node(
'i'
);
tree.root.left.right.left =
new
Node(
'j'
);
tree.root.left.right.right =
new
Node(
'k'
);
tree.root.right.left.left =
new
Node(
'l'
);
tree.root.right.left.right =
new
Node(
'm'
);
tree.root.right.right.left =
new
Node(
'n'
);
tree.root.right.right.right =
new
Node(
'o'
);
System.out.println(
"Inorder Traversal of given tree"
);
tree.printInorder();
tree.reverseAlternate();
System.out.println(
""
);
System.out.println(
""
);
System.out.println(
"Inorder Traversal of modified tree"
);
tree.printInorder();
}
}
// This code has been contributed by Mayank Jaiswal
|
n
|
390.java
| 0.5 |
// Java program to reverse alternate levels of a tree
class
Sol
{
static
class
Node
{
char
key;
Node left, right;
};
static
void
preorder( Node root1, Node root2,
int
lvl)
{
// Base cases
if
(root1 ==
null
|| root2==
null
)
return
;
// Swap subtrees if level is even
if
(lvl %
2
==
0
)
{
char
t = root1.key;
root1.key = root2.key;
root2.key = t;
}
// Recur for left and right subtrees (Note : left of root1
// is passed and right of root2 in first call and opposite
// in second call.
preorder(root1.left, root2.right, lvl+
1
);
preorder(root1.right, root2.left, lvl+
1
);
}
// This function calls preorder() for left and right children
// of root
static
void
reverseAlternate( Node root)
{
preorder(root.left, root.right,
0
);
}
// Inorder traversal (used to print initial and
// modified trees)
static
void
printInorder( Node root)
{
if
(root ==
null
)
return
;
printInorder(root.left);
System.out.print( root.key +
" "
);
printInorder(root.right);
}
// A utility function to create a new node
static
Node newNode(
int
key)
{
Node temp =
new
Node();
temp.left = temp.right =
null
;
temp.key = (
char
)key;
return
temp;
}
// Driver program to test above functions
public
static
void
main(String args[])
{
Node root = newNode(
'a'
);
root.left = newNode(
'b'
);
root.right = newNode(
'c'
);
root.left.left = newNode(
'd'
);
root.left.right = newNode(
'e'
);
root.right.left = newNode(
'f'
);
root.right.right = newNode(
'g'
);
root.left.left.left = newNode(
'h'
);
root.left.left.right = newNode(
'i'
);
root.left.right.left = newNode(
'j'
);
root.left.right.right = newNode(
'k'
);
root.right.left.left = newNode(
'l'
);
root.right.left.right = newNode(
'm'
);
root.right.right.left = newNode(
'n'
);
root.right.right.right = newNode(
'o'
);
System.out.print(
"Inorder Traversal of given tree\n"
);
printInorder(root);
reverseAlternate(root);
System.out.print(
"\n\nInorder Traversal of modified tree\n"
);
printInorder(root);
}
}
// This code is contributed by Arnab Kundu
|
n
|
391.java
| 0.5 |
// A java program for iterative postorder traversal using stack
import
java.util.ArrayList;
import
java.util.Stack;
// A binary tree node
class
Node
{
int
data;
Node left, right;
Node(
int
item)
{
data = item;
left = right;
}
}
class
BinaryTree
{
Node root;
ArrayList<Integer> list =
new
ArrayList<Integer>();
// An iterative function to do postorder traversal
// of a given binary tree
ArrayList<Integer> postOrderIterative(Node node)
{
Stack<Node> S =
new
Stack<Node>();
// Check for empty tree
if
(node ==
null
)
return
list;
S.push(node);
Node prev =
null
;
while
(!S.isEmpty())
{
Node current = S.peek();
/* go down the tree in search of a leaf an if so process it
and pop stack otherwise move down */
if
(prev ==
null
|| prev.left == current ||
prev.right == current)
{
if
(current.left !=
null
)
S.push(current.left);
else
if
(current.right !=
null
)
S.push(current.right);
else
{
S.pop();
list.add(current.data);
}
/* go up the tree from left node, if the child is right
push it onto stack otherwise process parent and pop
stack */
}
else
if
(current.left == prev)
{
if
(current.right !=
null
)
S.push(current.right);
else
{
S.pop();
list.add(current.data);
}
/* go up the tree from right node and after coming back
from right node process parent and pop stack */
}
else
if
(current.right == prev)
{
S.pop();
list.add(current.data);
}
prev = current;
}
return
list;
}
// Driver program to test above functions
public
static
void
main(String args[])
{
BinaryTree tree =
new
BinaryTree();
// Let us create trees shown in above diagram
tree.root =
new
Node(
1
);
tree.root.left =
new
Node(
2
);
tree.root.right =
new
Node(
3
);
tree.root.left.left =
new
Node(
4
);
tree.root.left.right =
new
Node(
5
);
tree.root.right.left =
new
Node(
6
);
tree.root.right.right =
new
Node(
7
);
ArrayList<Integer> mylist = tree.postOrderIterative(tree.root);
System.out.println(
"Post order traversal of binary tree is :"
);
System.out.println(mylist);
}
}
// This code has been contributed by Mayank Jaiswal
|
n
|
393.java
| 0.5 |
// Java program to print boundary traversal of binary tree
/* 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
item)
{
data = item;
left = right =
null
;
}
}
class
BinaryTree {
Node root;
// A simple function to print leaf nodes of a binary tree
void
printLeaves(Node node)
{
if
(node !=
null
) {
printLeaves(node.left);
// Print it if it is a leaf node
if
(node.left ==
null
&& node.right ==
null
)
System.out.print(node.data +
" "
);
printLeaves(node.right);
}
}
// A function to print all left boundary nodes, except a leaf node.
// Print the nodes in TOP DOWN manner
void
printBoundaryLeft(Node node)
{
if
(node !=
null
) {
if
(node.left !=
null
) {
// to ensure top down order, print the node
// before calling itself for left subtree
System.out.print(node.data +
" "
);
printBoundaryLeft(node.left);
}
else
if
(node.right !=
null
) {
System.out.print(node.data +
" "
);
printBoundaryLeft(node.right);
}
// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
}
// A function to print all right boundary nodes, except a leaf node
// Print the nodes in BOTTOM UP manner
void
printBoundaryRight(Node node)
{
if
(node !=
null
) {
if
(node.right !=
null
) {
// to ensure bottom up order, first call for right
// subtree, then print this node
printBoundaryRight(node.right);
System.out.print(node.data +
" "
);
}
else
if
(node.left !=
null
) {
printBoundaryRight(node.left);
System.out.print(node.data +
" "
);
}
// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
}
// A function to do boundary traversal of a given binary tree
void
printBoundary(Node node)
{
if
(node !=
null
) {
System.out.print(node.data +
" "
);
// Print the left boundary in top-down manner.
printBoundaryLeft(node.left);
// Print all leaf nodes
printLeaves(node.left);
printLeaves(node.right);
// Print the right boundary in bottom-up manner
printBoundaryRight(node.right);
}
}
// Driver program to test above functions
public
static
void
main(String args[])
{
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(
20
);
tree.root.left =
new
Node(
8
);
tree.root.left.left =
new
Node(
4
);
tree.root.left.right =
new
Node(
12
);
tree.root.left.right.left =
new
Node(
10
);
tree.root.left.right.right =
new
Node(
14
);
tree.root.right =
new
Node(
22
);
tree.root.right.right =
new
Node(
25
);
tree.printBoundary(tree.root);
}
}
|
n
|
394.java
| 0.5 |
// Java program to create complete Binary Tree from its Linked List
// representation
// importing necessary classes
import
java.util.*;
// A linked list node
class
ListNode
{
int
data;
ListNode next;
ListNode(
int
d)
{
data = d;
next =
null
;
}
}
// A binary tree node
class
BinaryTreeNode
{
int
data;
BinaryTreeNode left, right =
null
;
BinaryTreeNode(
int
data)
{
this
.data = data;
left = right =
null
;
}
}
class
BinaryTree
{
ListNode head;
BinaryTreeNode root;
// Function to insert a node at the beginning of
// the Linked List
void
push(
int
new_data)
{
// allocate node and assign data
ListNode new_node =
new
ListNode(new_data);
// link the old list off the new node
new_node.next = head;
// move the head to point to the new node
head = new_node;
}
// converts a given linked list representing a
// complete binary tree into the linked
// representation of binary tree.
BinaryTreeNode convertList2Binary(BinaryTreeNode node)
{
// queue to store the parent nodes
Queue<BinaryTreeNode> q =
new
LinkedList<BinaryTreeNode>();
// Base Case
if
(head ==
null
)
{
node =
null
;
return
null
;
}
// 1.) The first node is always the root node, and
// add it to the queue
node =
new
BinaryTreeNode(head.data);
q.add(node);
// advance the pointer to the next node
head = head.next;
// until the end of linked list is reached, do the
// following steps
while
(head !=
null
)
{
// 2.a) take the parent node from the q and
// remove it from q
BinaryTreeNode parent = q.peek();
BinaryTreeNode pp = q.poll();
// 2.c) take next two nodes from the linked list.
// We will add them as children of the current
// parent node in step 2.b. Push them into the
// queue so that they will be parents to the
// future nodes
BinaryTreeNode leftChild =
null
, rightChild =
null
;
leftChild =
new
BinaryTreeNode(head.data);
q.add(leftChild);
head = head.next;
if
(head !=
null
)
{
rightChild =
new
BinaryTreeNode(head.data);
q.add(rightChild);
head = head.next;
}
// 2.b) assign the left and right children of
// parent
parent.left = leftChild;
parent.right = rightChild;
}
return
node;
}
// Utility function to traverse the binary tree
// after conversion
void
inorderTraversal(BinaryTreeNode node)
{
if
(node !=
null
)
{
inorderTraversal(node.left);
System.out.print(node.data +
" "
);
inorderTraversal(node.right);
}
}
// Driver program to test above functions
public
static
void
main(String[] args)
{
BinaryTree tree =
new
BinaryTree();
tree.push(
36
);
/* Last node of Linked List */
tree.push(
30
);
tree.push(
25
);
tree.push(
15
);
tree.push(
12
);
tree.push(
10
);
/* First node of Linked List */
BinaryTreeNode node = tree.convertList2Binary(tree.root);
System.out.println(
"Inorder Traversal of the"
+
" constructed Binary Tree is:"
);
tree.inorderTraversal(node);
}
}
// This code has been contributed by Mayank Jaiswal
|
n
|
398.java
| 0.5 |
// Java program to construct binary tree from
// given array in level order fashion
public
class
Tree {
Node root;
// Tree Node
static
class
Node {
int
data;
Node left, right;
Node(
int
data)
{
this
.data = data;
this
.left =
null
;
this
.right =
null
;
}
}
// Function to insert nodes in level order
public
Node insertLevelOrder(
int
[] arr, Node root,
int
i)
{
// Base case for recursion
if
(i < arr.length) {
Node temp =
new
Node(arr[i]);
root = temp;
// insert left child
root.left = insertLevelOrder(arr, root.left,
2
* i +
1
);
// insert right child
root.right = insertLevelOrder(arr, root.right,
2
* i +
2
);
}
return
root;
}
// Function to print tree nodes in InOrder fashion
public
void
inOrder(Node root)
{
if
(root !=
null
) {
inOrder(root.left);
System.out.print(root.data +
" "
);
inOrder(root.right);
}
}
// Driver program to test above function
public
static
void
main(String args[])
{
Tree t2 =
new
Tree();
int
arr[] = {
1
,
2
,
3
,
4
,
5
,
6
,
6
,
6
,
6
};
t2.root = t2.insertLevelOrder(arr, t2.root,
0
);
t2.inOrder(t2.root);
}
}
|
n
|
399.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
|
4.java
| 0.5 |
// Java program to construct a binary tree from preorder traversal
// A Binary Tree node
class
Node
{
int
data;
Node left, right;
Node(
int
item)
{
data = item;
left = right =
null
;
}
}
class
Index
{
int
index =
0
;
}
class
BinaryTree
{
Node root;
Index myindex =
new
Index();
/* A recursive function to create a Binary Tree from given pre[]
preLN[] arrays. The function returns root of tree. index_ptr is used
to update index values in recursive calls. index must be initially
passed as 0 */
Node constructTreeUtil(
int
pre[],
char
preLN[], Index index_ptr,
int
n, Node temp)
{
// store the current value of index in pre[]
int
index = index_ptr.index;
// Base Case: All nodes are constructed
if
(index == n)
return
null
;
// Allocate memory for this node and increment index for
// subsequent recursive calls
temp =
new
Node(pre[index]);
(index_ptr.index)++;
// If this is an internal node, construct left and right subtrees
// and link the subtrees
if
(preLN[index] ==
'N'
)
{
temp.left = constructTreeUtil(pre, preLN, index_ptr, n,
temp.left);
temp.right = constructTreeUtil(pre, preLN, index_ptr, n,
temp.right);
}
return
temp;
}
// A wrapper over constructTreeUtil()
Node constructTree(
int
pre[],
char
preLN[],
int
n, Node node)
{
// Initialize index as 0. Value of index is used in recursion to
// maintain the current index in pre[] and preLN[] arrays.
int
index =
0
;
return
constructTreeUtil(pre, preLN, myindex, n, node);
}
/* This function is used only for testing */
void
printInorder(Node node)
{
if
(node ==
null
)
return
;
/* first recur on left child */
printInorder(node.left);
/* then print the data of node */
System.out.print(node.data +
" "
);
/* now recur on right child */
printInorder(node.right);
}
// driver function to test the above functions
public
static
void
main(String args[])
{
BinaryTree tree =
new
BinaryTree();
int
pre[] =
new
int
[]{
10
,
30
,
20
,
5
,
15
};
char
preLN[] =
new
char
[]{
'N'
,
'N'
,
'L'
,
'L'
,
'L'
};
int
n = pre.length;
// construct the above tree
Node mynode = tree.constructTree(pre, preLN, n, tree.root);
// Test the constructed tree
System.out.println(
"Following is Inorder Traversal of the"
+
"Constructed Binary Tree: "
);
tree.printInorder(mynode);
}
}
// This code has been contributed by Mayank Jaiswal
|
n
|
400.java
| 0.5 |
// Java program to convert BTT to DLL using
// simple inorder traversal
public
class
BinaryTreeToDLL
{
static
class
node
{
int
data;
node left, right;
public
node(
int
data)
{
this
.data = data;
}
}
static
node prev;
// Changes left pointers to work as previous
// pointers in converted DLL The function
// simply does inorder traversal of Binary
// Tree and updates left pointer using
// previously visited node
static
void
fixPrevptr(node root)
{
if
(root ==
null
)
return
;
fixPrevptr(root.left);
root.left = prev;
prev = root;
fixPrevptr(root.right);
}
// Changes right pointers to work
// as next pointers in converted DLL
static
node fixNextptr(node root)
{
// Find the right most node in
// BT or last node in DLL
while
(root.right !=
null
)
root = root.right;
// Start from the rightmost node, traverse
// back using left pointers. While traversing,
// change right pointer of nodes
while
(root !=
null
&& root.left !=
null
)
{
node left = root.left;
left.right = root;
root = root.left;
}
// The leftmost node is head of linked list, return it
return
root;
}
static
node BTTtoDLL(node root)
{
prev =
null
;
// Set the previous pointer
fixPrevptr(root);
// Set the next pointer and return head of DLL
return
fixNextptr(root);
}
// Traverses the DLL from left tor right
static
void
printlist(node root)
{
while
(root !=
null
)
{
System.out.print(root.data +
" "
);
root = root.right;
}
}
// Standard Inorder traversal of tree
static
void
inorder(node root)
{
if
(root ==
null
)
return
;
inorder(root.left);
System.out.print(root.data +
" "
);
inorder(root.right);
}
public
static
void
main(String[] args)
{
// Let us create the tree shown in above diagram
node root =
new
node(
10
);
root.left =
new
node(
12
);
root.right =
new
node(
15
);
root.left.left =
new
node(
25
);
root.left.right =
new
node(
30
);
root.right.left =
new
node(
36
);
System.out.println(
"Inorder Tree Traversal"
);
inorder(root);
node head = BTTtoDLL(root);
System.out.println(
"\nDLL Traversal"
);
printlist(head);
}
}
// This code is contributed by Rishabh Mahrsee
|
n
|
404.java
| 0.5 |
// A Java program for in-place conversion of Binary Tree to DLL
// A binary tree node has data, left pointers and right pointers
class
Node
{
int
data;
Node left, right;
public
Node(
int
data)
{
this
.data = data;
left = right =
null
;
}
}
class
BinaryTree
{
Node root;
// head --> Pointer to head node of created doubly linked list
Node head;
// Initialize previously visited node as NULL. This is
// static so that the same value is accessible in all recursive
// calls
static
Node prev =
null
;
// A simple recursive function to convert a given Binary tree
// to Doubly Linked List
// root --> Root of Binary Tree
void
BinaryTree2DoubleLinkedList(Node root)
{
// Base case
if
(root ==
null
)
return
;
// Recursively convert left subtree
BinaryTree2DoubleLinkedList(root.left);
// Now convert this node
if
(prev ==
null
)
head = root;
else
{
root.left = prev;
prev.right = root;
}
prev = root;
// Finally convert right subtree
BinaryTree2DoubleLinkedList(root.right);
}
/* Function to print nodes in a given doubly linked list */
void
printList(Node node)
{
while
(node !=
null
)
{
System.out.print(node.data +
" "
);
node = node.right;
}
}
// Driver program to test above functions
public
static
void
main(String[] args)
{
// Let us create the tree as shown in above diagram
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(
10
);
tree.root.left =
new
Node(
12
);
tree.root.right =
new
Node(
15
);
tree.root.left.left =
new
Node(
25
);
tree.root.left.right =
new
Node(
30
);
tree.root.right.left =
new
Node(
36
);
// convert to DLL
tree.BinaryTree2DoubleLinkedList(tree.root);
// Print the converted List
tree.printList(tree.head);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
|
n
|
405.java
| 0.5 |
// Java program to convert a given Binary Tree to
// Doubly Linked List
/* Structure for tree and Linked List */
class
Node
{
int
data;
Node left, right;
public
Node(
int
data)
{
this
.data = data;
left = right =
null
;
}
}
class
BinaryTree
{
// 'root' - root of binary tree
Node root;
// 'head' - reference to head node of created
//double linked list
Node head;
// A simple recursive function to convert a given
// Binary tree to Doubly Linked List
void
BToDLL(Node root)
{
// Base cases
if
(root ==
null
)
return
;
// Recursively convert right subtree
BToDLL(root.right);
// insert root into DLL
root.right = head;
// Change left pointer of previous head
if
(head !=
null
)
(head).left = root;
// Change head of Doubly linked list
head = root;
// Recursively convert left subtree
BToDLL(root.left);
}
// Utility function for printing double linked list.
void
printList(Node head)
{
System.out.println(
"Extracted Double Linked List is : "
);
while
(head !=
null
)
{
System.out.print(head.data +
" "
);
head = head.right;
}
}
// Driver program to test the above functions
public
static
void
main(String[] args)
{
/* Constructing below tree
5
/ \
3 6
/ \ \
1 4 8
/ \ / \
0 2 7 9 */
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(
5
);
tree.root.left =
new
Node(
3
);
tree.root.right =
new
Node(
6
);
tree.root.left.right =
new
Node(
4
);
tree.root.left.left =
new
Node(
1
);
tree.root.right.right =
new
Node(
8
);
tree.root.left.left.right =
new
Node(
2
);
tree.root.left.left.left =
new
Node(
0
);
tree.root.right.right.left =
new
Node(
7
);
tree.root.right.right.right =
new
Node(
9
);
tree.BToDLL(tree.root);
tree.printList(tree.head);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
|
n
|
406.java
| 0.5 |
/* Java program to convert left-right to
down-right representation of binary tree */
class
GFG
{
// A Binary Tree Node
static
class
node
{
int
key;
node left, right;
node(
int
key)
{
this
.key = key;
this
.left =
null
;
this
.right =
null
;
}
}
// An Iterative level order traversal
// based function to convert left-right
// to down-right representation.
static
void
convert(node root)
{
// Base Case
if
(root ==
null
)
return
;
// Recursively convert left
// an right subtrees
convert(root.left);
convert(root.right);
// If left child is NULL, make right
// child as left as it is the first child.
if
(root.left ==
null
)
root.left = root.right;
// If left child is NOT NULL, then make
// right child as right of left child
else
root.left.right = root.right;
// Set root's right as NULL
root.right =
null
;
}
// A utility function to traverse a
// tree stored in down-right form.
static
void
downRightTraversal(node root)
{
if
(root !=
null
)
{
System.out.print(root.key +
" "
);
downRightTraversal(root.right);
downRightTraversal(root.left);
}
}
// Utility function to create
// a new tree node
static
node newNode(
int
key)
{
node temp =
new
node(
0
);
temp.key = key;
temp.left =
null
;
temp.right =
null
;
return
temp;
}
// Driver Code
public
static
void
main(String[] args)
{
// Let us create binary tree
// shown in above diagram
/*
1
/ \
2 3
/ \
4 5
/ / \
6 7 8
*/
node root =
new
node(
1
);
root.left = newNode(
2
);
root.right = newNode(
3
);
root.right.left = newNode(
4
);
root.right.right = newNode(
5
);
root.right.left.left = newNode(
6
);
root.right.right.left = newNode(
7
);
root.right.right.right = newNode(
8
);
convert(root);
System.out.println(
"Traversal of the tree "
+
"converted to down-right form"
);
downRightTraversal(root);
}
}
// This code is contributed
// by Prerna Saini
|
n
|
408.java
| 0.5 |
// Java program to convert a tree into its sum tree
// A binary tree node
class
Node
{
int
data;
Node left, right;
Node(
int
item)
{
data = item;
left = right =
null
;
}
}
class
BinaryTree
{
Node root;
// Convert a given tree to a tree where every node contains sum of
// values of nodes in left and right subtrees in the original tree
int
toSumTree(Node node)
{
// Base case
if
(node ==
null
)
return
0
;
// Store the old value
int
old_val = node.data;
// Recursively call for left and right subtrees and store the sum
// as new value of this node
node.data = toSumTree(node.left) + toSumTree(node.right);
// Return the sum of values of nodes in left and right subtrees
// and old_value of this node
return
node.data + old_val;
}
// A utility function to print inorder traversal of a Binary Tree
void
printInorder(Node node)
{
if
(node ==
null
)
return
;
printInorder(node.left);
System.out.print(node.data +
" "
);
printInorder(node.right);
}
/* Driver function to test above functions */
public
static
void
main(String args[])
{
BinaryTree tree =
new
BinaryTree();
/* Constructing tree given in the above figure */
tree.root =
new
Node(
10
);
tree.root.left =
new
Node(-
2
);
tree.root.right =
new
Node(
6
);
tree.root.left.left =
new
Node(
8
);
tree.root.left.right =
new
Node(-
4
);
tree.root.right.left =
new
Node(
7
);
tree.root.right.right =
new
Node(
5
);
tree.toSumTree(tree.root);
// Print inorder traversal of the converted tree to test result
// of toSumTree()
System.out.println(
"Inorder Traversal of the resultant tree is:"
);
tree.printInorder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal
|
n
|
409.java
| 0.5 |
// Java program to store sum of nodes in left subtree in every
// node
class
GfG {
// A tree node
static
class
node
{
int
data;
node left, right;
}
// Function to modify a Binary Tree so that every node
// stores sum of values in its left child including its
// own value
static
int
updatetree(node root)
{
// Base cases
if
(root ==
null
)
return
0
;
if
(root.left ==
null
&& root.right ==
null
)
return
root.data;
// Update left and right subtrees
int
leftsum = updatetree(root.left);
int
rightsum = updatetree(root.right);
// Add leftsum to current node
root.data += leftsum;
// Return sum of values under root
return
root.data + rightsum;
}
// Utility function to do inorder traversal
static
void
inorder(node node)
{
if
(node ==
null
)
return
;
inorder(node.left);
System.out.print(node.data +
" "
);
inorder(node.right);
}
// Utility function to create a new node
static
node newNode(
int
data)
{
node node =
new
node();
node.data = data;
node.left =
null
;
node.right =
null
;
return
(node);
}
// Driver program
public
static
void
main(String[] args)
{
/* Let us construct below tree
1
/ \
2 3
/ \ \
4 5 6 */
node root = newNode(
1
);
root.left = newNode(
2
);
root.right = newNode(
3
);
root.left.left = newNode(
4
);
root.left.right = newNode(
5
);
root.right.right = newNode(
6
);
updatetree(root);
System.out.println(
"Inorder traversal of the modified tree is"
);
inorder(root);
}
}
|
n
|
410.java
| 0.5 |
// Java program to find maximum number to be removed
// to convert a tree into forest containg trees of
// even number of nodes
import
java.util.*;
class
GFG
{
static
int
N =
12
,ans;
static
Vector<Vector<Integer>> tree=
new
Vector<Vector<Integer>>();
// Return the number of nodes of subtree having
// node as a root.
static
int
dfs(
int
visit[],
int
node)
{
int
num =
0
, temp =
0
;
// Mark node as visited.
visit[node] =
1
;
// Traverse the adjacency list to find non-
// visited node.
for
(
int
i =
0
; i < tree.get(node).size(); i++)
{
if
(visit[tree.get(node).get(i)] ==
0
)
{
// Finding number of nodes of the subtree
// of a subtree.
temp = dfs( visit, tree.get(node).get(i));
// If nodes are even, increment number of
// edges to removed.
// Else leave the node as child of subtree.
if
(temp%
2
!=
0
)
num += temp;
else
ans++;
}
}
return
num+
1
;
}
// Return the maxium number of edge to remove
// to make forest.
static
int
minEdge(
int
n)
{
int
visit[] =
new
int
[n+
2
];
ans =
0
;
dfs( visit,
1
);
return
ans;
}
// Driven Program
public
static
void
main(String args[])
{
int
n =
10
;
//set the size of vector
for
(
int
i =
0
; i < n +
2
;i++)
tree.add(
new
Vector<Integer>());
tree.get(
1
).add(
3
);
tree.get(
3
).add(
1
);
tree.get(
1
).add(
6
);
tree.get(
6
).add(
1
);
tree.get(
1
).add(
2
);
tree.get(
2
).add(
1
);
tree.get(
3
).add(
4
);
tree.get(
4
).add(
3
);
tree.get(
6
).add(
8
);
tree.get(
8
).add(
6
);
tree.get(
2
).add(
7
);
tree.get(
7
).add(
2
);
tree.get(
2
).add(
5
);
tree.get(
5
).add(
2
);
tree.get(
4
).add(
9
);
tree.get(
9
).add(
4
);
tree.get(
4
).add(
10
);
tree.get(
10
).add(
4
);
System.out.println( minEdge( n));
}
}
// This code is contributed by Arnab Kundu
|
n
|
411.java
| 0.5 |
// Java program to covert a ternary
// expreesion to a tree.
import
java.util.Queue;
import
java.util.LinkedList;
// Class to represent Tree node
class
Node
{
char
data;
Node left, right;
public
Node(
char
item)
{
data = item;
left =
null
;
right =
null
;
}
}
// Class to covert a ternary expression to a Tree
class
BinaryTree
{
// Function to convert Ternary Expression to a Binary
// Tree. It return the root of tree
Node convertExpression(
char
[] expression,
int
i)
{
// Base case
if
(i >= expression.length)
return
null
;
// store current character of expression_string
// [ 'a' to 'z']
Node root =
new
Node(expression[i]);
// Move ahead in str
++i;
// if current character of ternary expression is '?'
// then we add next character as a left child of
// current node
if
(i < expression.length && expression[i]==
'?'
)
root.left = convertExpression(expression, i+
1
);
// else we have to add it as a right child of
// current node expression.at(0) == ':'
else
if
(i < expression.length)
root.right = convertExpression(expression, i+
1
);
return
root;
}
// function print tree
public
void
printTree( Node root)
{
if
(root ==
null
)
return
;
System.out.print(root.data +
" "
);
printTree(root.left);
printTree(root.right);
}
// Driver program to test above function
public
static
void
main(String args[])
{
String exp =
"a?b?c:d:e"
;
BinaryTree tree =
new
BinaryTree();
char
[] expression=exp.toCharArray();
Node root = tree.convertExpression(expression,
0
);
tree.printTree(root) ;
}
}
/* This code is contributed by Mr. Somesh Awasthi */
|
n
|
412.java
| 0.5 |
/* Java program to flip a binary tree */
import
java.util.Queue;
import
java.util.LinkedList;
public
class
FlipTree {
// method to flip the binary tree
public
static
Node flipBinaryTree(Node root)
{
if
(root ==
null
)
return
root;
if
(root.left ==
null
&& root.right ==
null
)
return
root;
// recursively call the same method
Node flippedRoot=flipBinaryTree(root.left);
// rearranging main root Node after returning
// from recursive call
root.left.left=root.right;
root.left.right=root;
root.left=root.right=
null
;
return
flippedRoot;
}
// Iterative method to do level order traversal
// line by line
public
static
void
printLevelOrder(Node root)
{
// Base Case
if
(root==
null
)
return
;
// Create an empty queue for level order traversal
Queue<Node> q=
new
LinkedList<>();
// Enqueue Root and initialize height
q.add(root);
while
(
true
)
{
// nodeCount (queue size) indicates number
// of nodes at current lelvel.
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.remove();
System.out.print(node.data+
" "
);
if
(node.left !=
null
)
q.add(node.left);
if
(node.right !=
null
)
q.add(node.right);
nodeCount--;
}
System.out.println();
}
}
public
static
void
main(String args[]) {
Node root=
new
Node(
1
);
root.left=
new
Node(
2
);
root.right=
new
Node(
1
);
root.right.left =
new
Node(
4
);
root.right.right =
new
Node(
5
);
System.out.println(
"Level order traversal of given tree"
);
printLevelOrder(root);
root = flipBinaryTree(root);
System.out.println(
"Level order traversal of flipped tree"
);
printLevelOrder(root);
}
}
/* A binary tree node structure */
class
Node
{
int
data;
Node left, right;
Node(
int
data)
{
this
.data=data;
}
};
//This code is contributed by Gaurav Tiwari
|
n
|
413.java
| 0.5 |
// Java program to flip a binary tree
import
java.util.*;
class
GFG
{
// A binary tree node
static
class
Node
{
int
data;
Node left, right;
};
// Utility function to create
// a new Binary Tree Node
static
Node newNode(
int
data)
{
Node temp =
new
Node();
temp.data = data;
temp.left = temp.right =
null
;
return
temp;
}
// method to flip the binary tree
static
Node flipBinaryTree(Node root)
{
// Initialization of pointers
Node curr = root;
Node next =
null
;
Node temp =
null
;
Node prev =
null
;
// Iterate through all left nodes
while
(curr !=
null
)
{
next = curr.left;
// Swapping nodes now, need
// temp to keep the previous
// right child
// Making prev's right
// as curr's left child
curr.left = temp;
// Storing curr's right child
temp = curr.right;
// Making prev as curr's
// right child
curr.right = prev;
prev = curr;
curr = next;
}
return
prev;
}
// Iterative method to do
// level order traversal
// line by line
static
void
printLevelOrder(Node root)
{
// Base Case
if
(root ==
null
)
return
;
// Create an empty queue for
// level order traversal
Queue<Node> q =
new
LinkedList<Node>();
// Enqueue Root and
// initialize height
q.add(root);
while
(
true
)
{
// nodeCount (queue size)
// indicates number of nodes
// at current lelvel.
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();
System.out.print(node.data +
" "
);
q.remove();
if
(node.left !=
null
)
q.add(node.left);
if
(node.right !=
null
)
q.add(node.right);
nodeCount--;
}
System.out.println();
}
}
// Driver code
public
static
void
main(String args[])
{
Node root = newNode(
1
);
root.left = newNode(
2
);
root.right = newNode(
3
);
root.right.left = newNode(
4
);
root.right.right = newNode(
5
);
System.out.print(
"Level order traversal "
+
"of given tree\n"
);
printLevelOrder(root);
root = flipBinaryTree(root);
System.out.print(
"\nLevel order traversal "
+
"of the flipped tree\n"
);
printLevelOrder(root);
}
}
// This code is contributed
// by Arnab Kundu
|
n
|
414.java
| 0.5 |
// Java program to check children sum property
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class
Node
{
int
data;
Node left, right;
public
Node(
int
d)
{
data = d;
left = right =
null
;
}
}
class
BinaryTree
{
Node root;
/* returns 1 if children sum property holds for the given
node and both of its children*/
int
isSumProperty(Node node)
{
/* left_data is left child data and right_data is for right
child data*/
int
left_data =
0
, right_data =
0
;
/* If node is NULL or it's a leaf node then
return true */
if
(node ==
null
|| (node.left ==
null
&& node.right ==
null
))
return
1
;
else
{
/* If left child is not present then 0 is used
as data of left child */
if
(node.left !=
null
)
left_data = node.left.data;
/* If right child is not present then 0 is used
as data of right child */
if
(node.right !=
null
)
right_data = node.right.data;
/* if the node and both of its children satisfy the
property return 1 else 0*/
if
((node.data == left_data + right_data)
&& (isSumProperty(node.left)!=
0
)
&& isSumProperty(node.right)!=
0
)
return
1
;
else
return
0
;
}
}
/* driver program to test the above functions */
public
static
void
main(String[] args)
{
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(
10
);
tree.root.left =
new
Node(
8
);
tree.root.right =
new
Node(
2
);
tree.root.left.left =
new
Node(
3
);
tree.root.left.right =
new
Node(
5
);
tree.root.right.right =
new
Node(
2
);
if
(tree.isSumProperty(tree.root) !=
0
)
System.out.println(
"The given tree satisfies children"
+
" sum property"
);
else
System.out.println(
"The given tree does not satisfy children"
+
" sum property"
);
}
}
|
n
|
415.java
| 0.5 |
// Java program to check if Binary tree is sum tree or not
/* A binary tree node has data, left child and right child */
class
Node
{
int
data;
Node left, right, nextRight;
Node(
int
item)
{
data = item;
left = right = nextRight =
null
;
}
}
class
BinaryTree
{
Node root;
/* Utility function to check if the given node is leaf or not */
int
isLeaf(Node node)
{
if
(node ==
null
)
return
0
;
if
(node.left ==
null
&& node.right ==
null
)
return
1
;
return
0
;
}
/* returns 1 if SumTree property holds for the given
tree */
int
isSumTree(Node node)
{
int
ls;
// for sum of nodes in left subtree
int
rs;
// for sum of nodes in right subtree
/* If node is NULL or it's a leaf node then
return true */
if
(node ==
null
|| isLeaf(node) ==
1
)
return
1
;
if
(isSumTree(node.left) !=
0
&& isSumTree(node.right) !=
0
)
{
// Get the sum of nodes in left subtree
if
(node.left ==
null
)
ls =
0
;
else
if
(isLeaf(node.left) !=
0
)
ls = node.left.data;
else
ls =
2
* (node.left.data);
// Get the sum of nodes in right subtree
if
(node.right ==
null
)
rs =
0
;
else
if
(isLeaf(node.right) !=
0
)
rs = node.right.data;
else
rs =
2
* (node.right.data);
/* If root's data is equal to sum of nodes in left
and right subtrees then return 1 else return 0*/
if
((node.data == rs + ls))
return
1
;
else
return
0
;
}
return
0
;
}
/* Driver program to test above functions */
public
static
void
main(String args[])
{
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(
26
);
tree.root.left =
new
Node(
10
);
tree.root.right =
new
Node(
3
);
tree.root.left.left =
new
Node(
4
);
tree.root.left.right =
new
Node(
6
);
tree.root.right.right =
new
Node(
3
);
if
(tree.isSumTree(tree.root) !=
0
)
System.out.println(
"The given tree is a sum tree"
);
else
System.out.println(
"The given tree is not a sum tree"
);
}
}
// This code has been contributed by Mayank Jaiswal
|
n
|
417.java
| 0.5 |
// Java program to check if two binary tree are cousins
class
Node
{
int
data;
Node left, right;
Node(
int
item)
{
data = item;
left = right =
null
;
}
}
class
BinaryTree
{
Node root;
// Recursive function to check if two Nodes are
// siblings
boolean
isSibling(Node node, Node a, Node b)
{
// Base case
if
(node ==
null
)
return
false
;
return
((node.left == a && node.right == b) ||
(node.left == b && node.right == a) ||
isSibling(node.left, a, b) ||
isSibling(node.right, a, b));
}
// Recursive function to find level of Node 'ptr' in
// a binary tree
int
level(Node node, Node ptr,
int
lev)
{
// base cases
if
(node ==
null
)
return
0
;
if
(node == ptr)
return
lev;
// Return level if Node is present in left subtree
int
l = level(node.left, ptr, lev +
1
);
if
(l !=
0
)
return
l;
// Else search in right subtree
return
level(node.right, ptr, lev +
1
);
}
// Returns 1 if a and b are cousins, otherwise 0
boolean
isCousin(Node node, Node a, Node b)
{
// 1. The two Nodes should be on the same level
// in the binary tree.
// 2. The two Nodes should not be siblings (means
// that they should not have the same parent
// Node).
return
((level(node, a,
1
) == level(node, b,
1
)) &&
(!isSibling(node, a, b)));
}
//Driver program to test above functions
public
static
void
main(String args[])
{
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(
1
);
tree.root.left =
new
Node(
2
);
tree.root.right =
new
Node(
3
);
tree.root.left.left =
new
Node(
4
);
tree.root.left.right =
new
Node(
5
);
tree.root.left.right.right =
new
Node(
15
);
tree.root.right.left =
new
Node(
6
);
tree.root.right.right =
new
Node(
7
);
tree.root.right.left.right =
new
Node(
8
);
Node Node1, Node2;
Node1 = tree.root.left.left;
Node2 = tree.root.right.right;
if
(tree.isCousin(tree.root, Node1, Node2))
System.out.println(
"Yes"
);
else
System.out.println(
"No"
);
}
}
// This code has been contributed by Mayank Jaiswal
|
n
|
418.java
| 0.5 |
// Java program to check if all leaves are at same level
// A binary tree node
class
Node
{
int
data;
Node left, right;
Node(
int
item)
{
data = item;
left = right =
null
;
}
}
class
Leaf
{
int
leaflevel=
0
;
}
class
BinaryTree
{
Node root;
Leaf mylevel =
new
Leaf();
/* Recursive function which checks whether all leaves are at same
level */
boolean
checkUtil(Node node,
int
level, Leaf leafLevel)
{
// Base case
if
(node ==
null
)
return
true
;
// If a leaf node is encountered
if
(node.left ==
null
&& node.right ==
null
)
{
// When a leaf node is found first time
if
(leafLevel.leaflevel ==
0
)
{
// Set first found leaf's level
leafLevel.leaflevel = level;
return
true
;
}
// If this is not first leaf node, compare its level with
// first leaf's level
return
(level == leafLevel.leaflevel);
}
// If this node is not leaf, recursively check left and right
// subtrees
return
checkUtil(node.left, level +
1
, leafLevel)
&& checkUtil(node.right, level +
1
, leafLevel);
}
/* The main function to check if all leafs are at same level.
It mainly uses checkUtil() */
boolean
check(Node node)
{
int
level =
0
;
return
checkUtil(node, level, mylevel);
}
public
static
void
main(String args[])
{
// Let us create the tree as shown in the example
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(
12
);
tree.root.left =
new
Node(
5
);
tree.root.left.left =
new
Node(
3
);
tree.root.left.right =
new
Node(
9
);
tree.root.left.left.left =
new
Node(
1
);
tree.root.left.right.left =
new
Node(
1
);
if
(tree.check(tree.root))
System.out.println(
"Leaves are at same level"
);
else
System.out.println(
"Leaves are not at same level"
);
}
}
// This code has been contributed by Mayank Jaiswal
|
n
|
419.java
| 0.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.