Instruction
stringlengths 261
35k
| Response
stringclasses 1
value |
---|---|
For this Question: Pino is super fond of candies. Today she has A chocolate candies, B orange candies, and C unknown candies. You are also given the happiness she gets after eating a particular candy.
She wants to have exactly X chocolate candies and Y orange candies. She can transform an unknown candy into a candy of any type (chocolate or orange).
Find the maximum happiness she can attain.The first line of input contains 5 integers X, Y, A, B, and C.
The second line contains an A integer corresponding to the happiness of the various chocolate candies.
The third line contains B integers corresponding to the happiness of the various orange candies.
The fourth line contains C integers corresponding to the happiness of the various unknown candies.
<b>Constraints:-</b>
1 <= A, B, C <= 100000
1 <= X <= A
1 <= Y <= B
1 <= happiness of any candy <= 1000000000 (10^9)Output a single integer, the maximum happiness Pino can achieve by eating the candies.Sample Input 1:-
1 2 2 2 1
2 4
5 1
3
Sample Output 1:-
12
Sample Input 2:-
2 2 2 2 2
8 6
9 1
2 1
Sample Output 2:-
25
<b>Explanation:-</b>
Pino eats the 2nd chocolate candy (happiness=4), then eats the 1st orange candy (happiness=4+5=9), then transforms the first unknown candy to orange candy and eats it (happiness=9+3=12), I have written this Solution Code: X, Y, A, B, C = [int(i) for i in input().split()]
t = X + Y
a = sorted([int(i) for i in input().split()])
b = sorted([int(i) for i in input().split()])
c = [int(i) for i in input().split()]
o = []
for i in range(A-1,-1,-1):
if (X) == 0:
break
else:
X -= 1
o.append(a[i])
for i in range(B-1,-1,-1):
if (Y) == 0:
break
else:
Y -= 1
o.append(b[i])
o.extend(c)
s = 0
o.sort()
for i in range(len(o)-1,-1,-1):
if t == 0:
break
else:
t -= 1
s += o[i]
print(s), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Pino is super fond of candies. Today she has A chocolate candies, B orange candies, and C unknown candies. You are also given the happiness she gets after eating a particular candy.
She wants to have exactly X chocolate candies and Y orange candies. She can transform an unknown candy into a candy of any type (chocolate or orange).
Find the maximum happiness she can attain.The first line of input contains 5 integers X, Y, A, B, and C.
The second line contains an A integer corresponding to the happiness of the various chocolate candies.
The third line contains B integers corresponding to the happiness of the various orange candies.
The fourth line contains C integers corresponding to the happiness of the various unknown candies.
<b>Constraints:-</b>
1 <= A, B, C <= 100000
1 <= X <= A
1 <= Y <= B
1 <= happiness of any candy <= 1000000000 (10^9)Output a single integer, the maximum happiness Pino can achieve by eating the candies.Sample Input 1:-
1 2 2 2 1
2 4
5 1
3
Sample Output 1:-
12
Sample Input 2:-
2 2 2 2 2
8 6
9 1
2 1
Sample Output 2:-
25
<b>Explanation:-</b>
Pino eats the 2nd chocolate candy (happiness=4), then eats the 1st orange candy (happiness=4+5=9), then transforms the first unknown candy to orange candy and eats it (happiness=9+3=12), I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d", &x)
#define sz(v) (int) v.size()
#define pr(v) For(i, 0, sz(v)) {cout<<v[i]<<" ";} cout<<endl;
#define slld(x) scanf("%lld", &x)
#define all(x) x.begin(), x.end()
#define For(i, st, en) for(ll i=st; i<en; i++)
#define tr(x) for(auto it=x.begin(); it!=x.end(); it++)
#define fast std::ios::sync_with_stdio(false);cin.tie(NULL);
#define pb push_back
#define ll long long
#define int long long
#define mp make_pair
#define F first
#define S second
typedef pair<int, int> pii;
typedef vector<int> vi;
#define MOD 1000000007
#define INF 1000000000000000007LL
const int N = 100005;
// it's swapnil07 ;)
#ifdef SWAPNIL07
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
cout << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
const char* comma = strchr(names + 1, ',');cout.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
int begtime = clock();
#define end_routine() cout << "\n\nTime elapsed: " << (clock() - begtime)*1000/CLOCKS_PER_SEC << " ms\n\n";
#else
#define endl '\n'
#define trace(...)
#define end_routine()
#endif
int red[N], grn[N], col[N];
signed main()
{
fast
#ifdef SWAPNIL07
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int x, y, a, b, c; cin>>x>>y>>a>>b>>c;
For(i, 0, a){
cin>>red[i];
}
For(i, 0, b){
cin>>grn[i];
}
For(i, 0, c){
cin>>col[i];
}
vector<int> vect;
sort(red, red+a); sort(grn, grn+b);
reverse(red, red+a); reverse(grn, grn+b);
For(i, 0, x){
vect.pb(red[i]);
}
For(i, 0, y){
vect.pb(grn[i]);
}
For(i, 0, c){
vect.pb(col[i]);
}
sort(all(vect));
reverse(all(vect));
int ans = 0;
For(i, 0, x+y){
ans+=vect[i];
}
cout<<ans;
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Pino is super fond of candies. Today she has A chocolate candies, B orange candies, and C unknown candies. You are also given the happiness she gets after eating a particular candy.
She wants to have exactly X chocolate candies and Y orange candies. She can transform an unknown candy into a candy of any type (chocolate or orange).
Find the maximum happiness she can attain.The first line of input contains 5 integers X, Y, A, B, and C.
The second line contains an A integer corresponding to the happiness of the various chocolate candies.
The third line contains B integers corresponding to the happiness of the various orange candies.
The fourth line contains C integers corresponding to the happiness of the various unknown candies.
<b>Constraints:-</b>
1 <= A, B, C <= 100000
1 <= X <= A
1 <= Y <= B
1 <= happiness of any candy <= 1000000000 (10^9)Output a single integer, the maximum happiness Pino can achieve by eating the candies.Sample Input 1:-
1 2 2 2 1
2 4
5 1
3
Sample Output 1:-
12
Sample Input 2:-
2 2 2 2 2
8 6
9 1
2 1
Sample Output 2:-
25
<b>Explanation:-</b>
Pino eats the 2nd chocolate candy (happiness=4), then eats the 1st orange candy (happiness=4+5=9), then transforms the first unknown candy to orange candy and eats it (happiness=9+3=12), I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String str[] = read.readLine().split(" ");
int X = Integer.parseInt(str[0]);
int Y = Integer.parseInt(str[1]);
int A = Integer.parseInt(str[2]);
int B = Integer.parseInt(str[3]);
int C = Integer.parseInt(str[4]);
int arr[] = new int[X+Y+C];
int arrA[] = new int[A];
int arrB[] = new int[B];
int arrC[] = new int[C];
String strA[] = read.readLine().split(" ");
for(int k = 0; k < A; k++) {
arrA[k] = Integer.parseInt(strA[k]);
}
Arrays.sort(arrA);
String strB[] = read.readLine().split(" ");
for(int p = 0; p < B; p++) {
arrB[p] = Integer.parseInt(strB[p]);
}
Arrays.sort(arrB);
String strC[] = read.readLine().split(" ");
for(int q = 0; q < C; q++) {
arrC[q] = Integer.parseInt(strC[q]);
}
Arrays.sort(arrC);
System.arraycopy(arrA, arrA.length - X, arr, 0, X);
System.arraycopy(arrB, arrB.length - Y, arr, X, Y);
System.arraycopy(arrC, 0, arr, X+Y, C);
Arrays.sort(arr);
long happiness = 0;
int lastIndex = arr.length - 1;
int candies = 0;
for(int z = lastIndex; z >= 0; z--) {
happiness += arr[z];
candies++;
if(candies == X + Y) {
break;
}
}
System.out.print(happiness);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given the first 2 terms A and B of an Arithmetic Series, tell the Nth term of the series.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>NthAP()</b> that takes the integer A, B, and N as a parameter.
<b>Constraints:</b>
-10<sup>3</sup> ≤ A ≤ 10<sup>3</sup>
-10<sup>3</sup> ≤ B ≤ 10<sup>3</sup>
1 ≤ N ≤ 10<sup>4</sup>Return the Nth term of AP series.Sample Input 1:
2 3 4
Sample Output 1:
5
Sample Input 2:
1 2 10
Sample output 2:
10, I have written this Solution Code: class Solution {
public static int NthAP(int a, int b, int n){
return a+(n-1)*(b-a);
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find the number of prime numbers before N (Including that number too).The first line of the input contains the number of test cases T.
Next T lines contain the value N.
<b>Constraints</b>
1 <= T <= 1e5
1 <= N <= 1e5Print the number of primes number before that number.Sample Input 1:
2
3
11
Sample Output 1:
2
5, I have written this Solution Code: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
class Main
{
static int [] booleanArray(int num)
{
boolean [] bool = new boolean[num+1];
int [] count = new int [num+1];
bool[0] = true;
bool[1] = true;
for(int i=2; i*i<=num; i++)
{
if(bool[i]==false)
{
for(int j=i*i; j<=num; j+=i)
bool[j] = true;
}
}
int counter = 0;
for(int i=1; i<=num; i++)
{
if(bool[i]==false)
{
counter = counter+1;
count[i] = counter;
}
else
{
count[i] = counter;
}
}
return count;
}
public static void main (String[] args) throws IOException {
InputStreamReader ak = new InputStreamReader(System.in);
BufferedReader hk = new BufferedReader(ak);
int[] v = booleanArray(100000);
int t = Integer.parseInt(hk.readLine());
for (int i = 1; i <= t; i++) {
int a = Integer.parseInt(hk.readLine());
System.out.println(v[a]);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find the number of prime numbers before N (Including that number too).The first line of the input contains the number of test cases T.
Next T lines contain the value N.
<b>Constraints</b>
1 <= T <= 1e5
1 <= N <= 1e5Print the number of primes number before that number.Sample Input 1:
2
3
11
Sample Output 1:
2
5, I have written this Solution Code: m=100001
prime=[True for i in range(m)]
p=2
while(p*p<=m):
if prime[p]:
for i in range(p*p,m,p):
prime[i]=False
p+=1
c=[0 for i in range(m)]
c[2]=1
for i in range(3,m):
if prime[i]:
c[i]=c[i-1]+1
else:
c[i]=c[i-1]
t=int(input())
while t>0:
n=int(input())
print(c[n])
t-=1, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find the number of prime numbers before N (Including that number too).The first line of the input contains the number of test cases T.
Next T lines contain the value N.
<b>Constraints</b>
1 <= T <= 1e5
1 <= N <= 1e5Print the number of primes number before that number.Sample Input 1:
2
3
11
Sample Output 1:
2
5, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 2351
#endif
vector<bool> sieve(int n) {
vector<bool> is_prime(n + 1, true);
is_prime[0] = is_prime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (is_prime[i]) {
for (int j = i * i; j <= n; j += i)
is_prime[j] = false;
}
}
return is_prime;
}
int main() {
vector<bool> prime = sieve(1e5 + 1);
vector<int> prefix(1e5 + 1, 0);
for (int i = 1; i <= 1e5; i++) {
if (prime[i]) {
prefix[i] = prefix[i - 1] + 1;
} else {
prefix[i] = prefix[i - 1];
}
}
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
cout << prefix[n] << "\n";
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S. Two position i and j of the string are friends if they have the same character. The distance between two friends at positions i and j is defined as |i- j|. Find the sum of distances of all the pairs of friends in the given strings.First line of input contains a single string S.
Constraints:
1 <= |S| <= 1000000
String contains lowercase english letters.Output a single integer which is the sum of distance of all the pair of friends in the given strings.Sample Input
ababa
Sample Output
10
Explanation: Friend pairs - (1, 3) (1, 5) (2, 4) (3, 5), I have written this Solution Code: import java.io.*;
import java.io.IOException;
import java.util.*;
class Main {
public static long mod = (long)Math.pow(10,9)+7 ;
public static double epsilon=0.00000000008854;
public static InputReader sc = new InputReader(System.in);
public static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) {
String s=sc.nextLine();
int n=s.length();
int hnum[]=new int[26];
int hpast[]=new int[26];
Arrays.fill(hpast,-1);
long hsum[]=new long[26];
long ans=0;
for(int i=0;i<n;i++){
int k=s.charAt(i)-'a';
if(hpast[k]!=-1)
hsum[k]=hsum[k]+(i-hpast[k])*hnum[k];
ans+=hsum[k];
hnum[k]++;
hpast[k]=i;
}
pw.println(ans);
pw.flush();
pw.close();
}
public static Comparator<Long[]> column(int i){
return
new Comparator<Long[]>() {
@Override
public int compare(Long[] o1, Long[] o2) {
return o1[i].compareTo(o2[i]);
}
};
}
public static Comparator<Integer[]> col(int i){
return
new Comparator<Integer[]>() {
@Override
public int compare(Integer[] o1, Integer[] o2) {
return o1[i].compareTo(o2[i]);
}
};
}
public static String reverseString(String s){
StringBuilder input1 = new StringBuilder();
input1.append(s);
input1 = input1.reverse();
return input1.toString();
}
public static int[] scanArray(int n){
int a[]=new int [n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
return a;
}
public static long[] scanLongArray(int n){
long a[]=new long [n];
for(int i=0;i<n;i++)
a[i]=sc.nextLong();
return a;
}
public static String [] scanStrings(int n){
String a[]=new String [n];
for(int i=0;i<n;i++)
a[i]=sc.nextLine();
return a;
}
public static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
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 = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} 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 = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S. Two position i and j of the string are friends if they have the same character. The distance between two friends at positions i and j is defined as |i- j|. Find the sum of distances of all the pairs of friends in the given strings.First line of input contains a single string S.
Constraints:
1 <= |S| <= 1000000
String contains lowercase english letters.Output a single integer which is the sum of distance of all the pair of friends in the given strings.Sample Input
ababa
Sample Output
10
Explanation: Friend pairs - (1, 3) (1, 5) (2, 4) (3, 5), I have written this Solution Code: def findS(s):
visited= [ 0 for i in range(256)];
distance =[0 for i in range (256)];
for i in range(256):
visited[i]=0;
distance[i]=0;
sum=0;
for i in range(len(s)):
sum+=visited[ord(s[i])] * i - distance[ord(s[i])];
visited[ord(s[i])] +=1;
distance[ord(s[i])] +=i;
return sum;
if __name__ == '__main__':
s=input("");
print(findS(s));, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S. Two position i and j of the string are friends if they have the same character. The distance between two friends at positions i and j is defined as |i- j|. Find the sum of distances of all the pairs of friends in the given strings.First line of input contains a single string S.
Constraints:
1 <= |S| <= 1000000
String contains lowercase english letters.Output a single integer which is the sum of distance of all the pair of friends in the given strings.Sample Input
ababa
Sample Output
10
Explanation: Friend pairs - (1, 3) (1, 5) (2, 4) (3, 5), I have written this Solution Code: #pragma GCC optimize ("O3")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> oset;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
string s;
cin>>s;
int c[26]={};
int f[26]={};
int ans=0;
int n=s.length();
for(int i=0;i<n;++i){
ans+=f[s[i]-'a']*i-c[s[i]-'a'];
f[s[i]-'a']++;
c[s[i]-'a']+=i;
}
cout<<ans;
#ifdef ANIKET_GOYAL
// cout<<endl<<endl<<endl<<endl<<"Time elapsed: "<<(double)(clock()-clk)/CLOCKS_PER_SEC<<endl;
#endif
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For an integer N, your task is to calculate sum of first N natural numbers.<b>User Task:</b>
Since this will be a functional problem, you don't have to worry about input. You just have to complete the function <b>sum()</b> which takes the integer N as a parameter.
Constraints:
1 <= N < = 100000000Print the sum of first N natural numbers.Sample Input:-
5
Sample Output:-
15
Sample Input:-
3
Sample Output:-
6, I have written this Solution Code:
static void sum(int N){
long x=N;
x=x*(x+1);
x=x/2;
System.out.print(x);
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an undirected graph, the task is to detect if there is a cycle in the undirected graph or not.The first line of input contains two integers N and M which denotes the no of vertices and no of edges in the graph respectively.
Next M lines contain space-separated integers u and v denoting that there is a directed edge from u to v.
Constraints:
1 <= N, M <= 1000
0 <= u, v <= N-1, u != v
There are no self loops or multiple edges.
Print 'Yes' if there is a cycle in the graph otherwise print 'No'Sample Input 1:
4 5
0 1
1 2
2 3
3 0
0 2
Sample Output 1:
Yes
Explanation:
There is a cycle with nodes 0, 1, 2, 3
Sample Input 2:
4 3
0 1
1 2
2 3
Sample Output 2:
No
Explanation:
There is no cycle in this graph, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
static ArrayList<Integer> ar[];
static boolean st[];
static boolean status=false;
public static void main (String[] args) throws Exception {
BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));
try{
String sa[]=rd.readLine().split(" ");
int n=Integer.parseInt(sa[0]);
int e=Integer.parseInt(sa[1]);
st=new boolean[n+1];
ar=new ArrayList[n+1];
for(int i=0;i<n;i++)
ar[i]=new ArrayList<Integer>();
for(int i=0;i<e;i++)
{
sa=rd.readLine().split(" ");
int u=Integer.parseInt(sa[0]);;
int v=Integer.parseInt(sa[1]);;
ar[u].add(v);
ar[v].add(u);
}
dfs(0);
if(status)
System.out.println("Yes");
else
System.out.println("No");
}
catch(Exception e)
{
if(status)
System.out.println("Yes");
else
System.out.println("Yes");
}
}
static int p=-1;
static void dfs(int k)
{
try{
Stack <Integer> st1=new Stack<>();
int l=0;
st1.add(k);
while(!st1.empty())
{
if(!st1.empty())
l=st1.pop();
if(st[l])
{
status=true;
return;
}
st[l]=true;
for(int i=0;i<ar[l].size();i++)
{
if(!st[ar[l].get(i)])
st1.push(ar[l].get(i));
}
}
}
catch(Exception e)
{
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an undirected graph, the task is to detect if there is a cycle in the undirected graph or not.The first line of input contains two integers N and M which denotes the no of vertices and no of edges in the graph respectively.
Next M lines contain space-separated integers u and v denoting that there is a directed edge from u to v.
Constraints:
1 <= N, M <= 1000
0 <= u, v <= N-1, u != v
There are no self loops or multiple edges.
Print 'Yes' if there is a cycle in the graph otherwise print 'No'Sample Input 1:
4 5
0 1
1 2
2 3
3 0
0 2
Sample Output 1:
Yes
Explanation:
There is a cycle with nodes 0, 1, 2, 3
Sample Input 2:
4 3
0 1
1 2
2 3
Sample Output 2:
No
Explanation:
There is no cycle in this graph, I have written this Solution Code:
def dfs(adjList,vis,start,prev):
vis[start]=True
for i in adjList[start]:
if i == prev:
continue
if vis[i]:
return True
else:
dfs(adjList,vis,i,start)
return False
np=list(map(int,input().rstrip().split()))
n=np[0]
e=np[1]
adjList = [[] for i in range(n+1)]
for i in range(e):
edge = list(map(int,input().rstrip().split()))
adjList[edge[0]].append(edge[1])
adjList[edge[1]].append(edge[0])
vis = [False for i in range(n+1)]
flag=0
for i in range(n):
if not vis[i]:
if dfs(adjList,vis,i,0):
flag=1
break
if flag:
print("Yes")
else:
print("No"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an undirected graph, the task is to detect if there is a cycle in the undirected graph or not.The first line of input contains two integers N and M which denotes the no of vertices and no of edges in the graph respectively.
Next M lines contain space-separated integers u and v denoting that there is a directed edge from u to v.
Constraints:
1 <= N, M <= 1000
0 <= u, v <= N-1, u != v
There are no self loops or multiple edges.
Print 'Yes' if there is a cycle in the graph otherwise print 'No'Sample Input 1:
4 5
0 1
1 2
2 3
3 0
0 2
Sample Output 1:
Yes
Explanation:
There is a cycle with nodes 0, 1, 2, 3
Sample Input 2:
4 3
0 1
1 2
2 3
Sample Output 2:
No
Explanation:
There is no cycle in this graph, I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
vector<int> g[N];
int vis[N];
bool flag = 0;
void dfs(int u, int p){
vis[u] = 1;
for(auto i: g[u]){
if(i == p) continue;
if(vis[i] == 1)
flag = 1;
if(vis[i] == 0) dfs(i, u);
}
vis[u] = 2;
}
signed main() {
IOS;
int n, m;
cin >> n >> m;
for(int i = 1; i <= m; i++){
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
for(int i = 0; i < n; i++){
if(vis[i]) continue;
dfs(i, n);
}
if(flag)
cout << "Yes";
else
cout << "No";
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N elements and an integer D. Your task is to rotate the array D times in a circular manner from the right to left direction. Consider the examples for better understanding:-
Try to do without creating another arrayUser task:
Since this will be a functional problem, you don't have to take input. You just have to complete the functions <b>rotate()</b> that takes the array, size of the array, and the integer d as a parameter.
Constraints:
1 <= T <= 25
2 <= N <= 10^4
1<=D<=10^5
1 <= A[i] <= 10^5For each test case, you just need to rotate the array by D times. The driver code will prin the rotated array in a new line.Sample Input:
2
8
4
1 2 3 4 5 6 7 8
10
3
1 2 3 4 5 6 7 8 9 10
Sample Output:
5 6 7 8 1 2 3 4
4 5 6 7 8 9 10 1 2 3
Explanation(might now be the optimal solution):
Testcase 1:
Follow the below steps:-
After the first rotation, the array becomes 2 3 4 5 6 7 8 1
After the second rotation, the array becomes 3 4 5 6 7 8 1 2
After the third rotation, the array becomes 4 5 6 7 8 1 2 3
After the fourth rotation, the array becomes 5 6 7 8 1 2 3 4
Hence the final result: 5 6 7 8 1 2 3 4, I have written this Solution Code: public static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
public static void rotate(int arr[], int n, int d){
d = d % n;
int g_c_d = gcd(d, n);
for (int i = 0; i < g_c_d; i++) {
/* move i-th values of blocks */
int temp = arr[i];
int j = i;
boolean win=true;
while (win) {
int k = j + d;
if (k >= n)
k = k - n;
if (k == i)
break;
arr[j] = arr[k];
j = k;
}
arr[j] = temp;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Everyone is so excited about the upcoming cricket championship, so they decided to have a fun event before the start, in which they will be conducting a dummy tournament but the winner will be decided on the basis of the supporters of the team. There are <b>2^K</b> teams participating in this tournament named from Team 1, Team 2, to Team 2^K, and there will be exactly 2^K -1 matches (knockout tournament).
<b>Winning Criteria: The winner of the match will be decided by the number of supporters i.e. team having more supporters will win the match. If the number of supporters are same then the winning team will be the one that has a lower team number.</b>
<b><i>There is one more twist, the supporters of the losing team will join the supporters of the team which is going against the team who eliminated their team.</i></b>
Thus matches which is going to be played in tournament will take place in below format:
Match 1: team 1 vs team 2,
winner: team 1(if team 1 supporter is more than team 2)
Match 2: team 3 vs team 4.
winner: team 3(if team 3 supporter is more than team 4)
Match 3: team 1 vs team 3 (team 2 supporter joins team 3 and team 4 supporters joins team 1)
Your task is to find the number of supporters of the team which wins the tournament.The first line of input contains a single integer K. The next line contains 2^K space separated integers depicting the supporters of each team.
<b>Constraints:-</b>
1 <= K <= 16
1 <= Supporters <= 100000Print the number of supporters of the winning team.Sample Input:-
3
2 3 4 1 3 5 6 8
Sample Output:-
17
Explanation:-
1 vs 2:- 2(3)
3 vs 4:- 3(4)
5 vs 6:- 6(5)
7 vs 8:- 8(8)
2(3+1) vs 3(4+2):- 3(6)
6(5+6) vs 8(8+3):- 6(11)
3(6+11) vs 6(11+4):- 3(17)
Sample Input:-
3
4 1 2 3 4 3 2 1
Sample Output:-
11, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = (int)Math.pow(2,Integer.parseInt(br.readLine()));
int[] arr = new int[n];
String str1 = br.readLine();
String str2[] = str1.split(" ");
for(int i = 0; i < n; ++i) {
arr[i] = Integer.parseInt(str2[i]);
}
Queue<Integer> win = new LinkedList<>();
Queue<Integer> loss = new LinkedList<>();
for(int i = 0; i < n; i+=2) {
if(arr[i] > arr[i+1]) {
win.add(arr[i]);
loss.add(arr[i+1]);
} else {
win.add(arr[i+1]);
loss.add(arr[i]);
}
}
while(win.size() > 1) {
int Firstwinner = win.remove();
int secondwinner = win.remove();
int Firstloser = loss.remove();
int secondloser = loss.remove();
win.add(Math.max(Firstwinner+secondloser,secondwinner+Firstloser));
loss.add(Math.min(Firstwinner+secondloser,secondwinner+Firstloser));
}
System.out.print(win.remove());
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Everyone is so excited about the upcoming cricket championship, so they decided to have a fun event before the start, in which they will be conducting a dummy tournament but the winner will be decided on the basis of the supporters of the team. There are <b>2^K</b> teams participating in this tournament named from Team 1, Team 2, to Team 2^K, and there will be exactly 2^K -1 matches (knockout tournament).
<b>Winning Criteria: The winner of the match will be decided by the number of supporters i.e. team having more supporters will win the match. If the number of supporters are same then the winning team will be the one that has a lower team number.</b>
<b><i>There is one more twist, the supporters of the losing team will join the supporters of the team which is going against the team who eliminated their team.</i></b>
Thus matches which is going to be played in tournament will take place in below format:
Match 1: team 1 vs team 2,
winner: team 1(if team 1 supporter is more than team 2)
Match 2: team 3 vs team 4.
winner: team 3(if team 3 supporter is more than team 4)
Match 3: team 1 vs team 3 (team 2 supporter joins team 3 and team 4 supporters joins team 1)
Your task is to find the number of supporters of the team which wins the tournament.The first line of input contains a single integer K. The next line contains 2^K space separated integers depicting the supporters of each team.
<b>Constraints:-</b>
1 <= K <= 16
1 <= Supporters <= 100000Print the number of supporters of the winning team.Sample Input:-
3
2 3 4 1 3 5 6 8
Sample Output:-
17
Explanation:-
1 vs 2:- 2(3)
3 vs 4:- 3(4)
5 vs 6:- 6(5)
7 vs 8:- 8(8)
2(3+1) vs 3(4+2):- 3(6)
6(5+6) vs 8(8+3):- 6(11)
3(6+11) vs 6(11+4):- 3(17)
Sample Input:-
3
4 1 2 3 4 3 2 1
Sample Output:-
11, I have written this Solution Code: k = int(input())
s = list(map(int, input().split()))
tourney = []
for i in range(k + 1):
bracket = []
if i == 0:
for j in range((2**(k + 1 - i)) // 2):
bracket.append([s[j], 0])
else:
for k in range(1, len(tourney[i-1]), 2):
bracket.append( [max( tourney[i-1][k-1][0] + tourney[i-1][k][1], tourney[i-1][k][0] + tourney[i-1][k-1][1] ),
min( tourney[i-1][k-1][0] + tourney[i-1][k][1], tourney[i-1][k][0] + tourney[i-1][k-1][1] )] )
tourney.append(bracket)
'''
for b in tourney:
print(b)
print()
'''
print(tourney[len(tourney) - 1][0][0]), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Everyone is so excited about the upcoming cricket championship, so they decided to have a fun event before the start, in which they will be conducting a dummy tournament but the winner will be decided on the basis of the supporters of the team. There are <b>2^K</b> teams participating in this tournament named from Team 1, Team 2, to Team 2^K, and there will be exactly 2^K -1 matches (knockout tournament).
<b>Winning Criteria: The winner of the match will be decided by the number of supporters i.e. team having more supporters will win the match. If the number of supporters are same then the winning team will be the one that has a lower team number.</b>
<b><i>There is one more twist, the supporters of the losing team will join the supporters of the team which is going against the team who eliminated their team.</i></b>
Thus matches which is going to be played in tournament will take place in below format:
Match 1: team 1 vs team 2,
winner: team 1(if team 1 supporter is more than team 2)
Match 2: team 3 vs team 4.
winner: team 3(if team 3 supporter is more than team 4)
Match 3: team 1 vs team 3 (team 2 supporter joins team 3 and team 4 supporters joins team 1)
Your task is to find the number of supporters of the team which wins the tournament.The first line of input contains a single integer K. The next line contains 2^K space separated integers depicting the supporters of each team.
<b>Constraints:-</b>
1 <= K <= 16
1 <= Supporters <= 100000Print the number of supporters of the winning team.Sample Input:-
3
2 3 4 1 3 5 6 8
Sample Output:-
17
Explanation:-
1 vs 2:- 2(3)
3 vs 4:- 3(4)
5 vs 6:- 6(5)
7 vs 8:- 8(8)
2(3+1) vs 3(4+2):- 3(6)
6(5+6) vs 8(8+3):- 6(11)
3(6+11) vs 6(11+4):- 3(17)
Sample Input:-
3
4 1 2 3 4 3 2 1
Sample Output:-
11, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define int long long
int solve(int a[], int n){
if(n==1){return a[0];}
int ans[n/2]={0};
if(n==2){
return max(a[0],a[1]);
}
for(int i=0;i<n;i+=4){
if(a[i]>=a[i+1]){
ans[i/2]+=a[i];
ans[i/2+1]+=a[i+1];
}
else{
ans[i/2+1]+=a[i];
ans[i/2]+=a[i+1];
}
if(a[i+2]>=a[i+3]){
ans[i/2+1]+=a[i+2];
ans[i/2]+=a[i+3];
}
else{
ans[i/2]+=a[i+2];
ans[i/2+1]+=a[i+3];
}
}
return solve(ans,n/2);
}
signed main(){
int x;
cin>>x;
int n = 1;
for(int i=0;i<x;i++){
n*=2;
}
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
cout<<solve(a,n);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a saying in Sara's village that "A number is called prime if the sum of all the factors of N is less than or equal to (3*N)/2 ". Given the number N, your task is to check if it is a myth or a fact for the number given.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>mythOrFact()</b> that takes integer N as argument.
Constraints:-
2 <= N <= 1000Return 1 if it is a fact else return 0.Sample Input:-
2
Sample Output:-
1
Explanation:-
Sum = 2 + 1 = 3
3*(2) / 2 = 3
Sample Input:-
9
Sample Output:-
0, I have written this Solution Code:
int mythOrFact(int N){
int prime =1;
int cnt = N+1;
for(int i=2;i<N;i++){
if(N%i==0){cnt+=i;prime=0;}
}
int p = 3*N;
p/=2;
if((cnt<=p && prime==1) || (cnt>p && prime==0) ){return 1;}
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a saying in Sara's village that "A number is called prime if the sum of all the factors of N is less than or equal to (3*N)/2 ". Given the number N, your task is to check if it is a myth or a fact for the number given.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>mythOrFact()</b> that takes integer N as argument.
Constraints:-
2 <= N <= 1000Return 1 if it is a fact else return 0.Sample Input:-
2
Sample Output:-
1
Explanation:-
Sum = 2 + 1 = 3
3*(2) / 2 = 3
Sample Input:-
9
Sample Output:-
0, I have written this Solution Code:
int mythOrFact(int N){
int prime =1;
int cnt = N+1;
for(int i=2;i<N;i++){
if(N%i==0){cnt+=i;prime=0;}
}
int p = 3*N;
p/=2;
if((cnt<=p && prime==1) || (cnt>p && prime==0) ){return 1;}
return 0;
}
, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a saying in Sara's village that "A number is called prime if the sum of all the factors of N is less than or equal to (3*N)/2 ". Given the number N, your task is to check if it is a myth or a fact for the number given.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>mythOrFact()</b> that takes integer N as argument.
Constraints:-
2 <= N <= 1000Return 1 if it is a fact else return 0.Sample Input:-
2
Sample Output:-
1
Explanation:-
Sum = 2 + 1 = 3
3*(2) / 2 = 3
Sample Input:-
9
Sample Output:-
0, I have written this Solution Code: static int mythOrFact(int N){
int prime =1;
int cnt = N+1;
for(int i=2;i<N;i++){
if(N%i==0){cnt+=i;prime=0;}
}
int p = 3*N;
p/=2;
if((cnt<=p && prime==1) || (cnt>p && prime==0) ){return 1;}
return 0;
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is a saying in Sara's village that "A number is called prime if the sum of all the factors of N is less than or equal to (3*N)/2 ". Given the number N, your task is to check if it is a myth or a fact for the number given.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>mythOrFact()</b> that takes integer N as argument.
Constraints:-
2 <= N <= 1000Return 1 if it is a fact else return 0.Sample Input:-
2
Sample Output:-
1
Explanation:-
Sum = 2 + 1 = 3
3*(2) / 2 = 3
Sample Input:-
9
Sample Output:-
0, I have written this Solution Code: def mythOrFact(N):
prime=1
cnt=N+1
for i in range (2,N):
if N%i==0:
prime=0
cnt=cnt+i
x = 3*N
x=x//2
if(cnt <= x and prime==1) or (cnt>x and prime==0):
return 1
return 0
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a Binary Tree containing <b>N</b> nodes. The task is to print the nodes of binary tree in ZigZag manner. Below diagram shows nodes of binary tree printed in ZigZag manner.
<b>ZigZag:</b> While traversing binary tree level wise you have print the nodes from left to right and then right to left alternatively i.e. first level from left to right, next level right to left, then again left to right and so on.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>zigZagTraversa()</b> that takes "root" node as parameter and The printing is done by the driver code.
<b>Constraints:</b>
1 <= T <= 50
1 <= N <= 10^4
<b>Sum of N over all testcases does not exceed 10^5</b>
For each test case you need to return the ArrayList containing node values of binary tree in ZigZag manner. The driver code will take care of printing them up.Input:
2
3 2 1
7 7 9 8 8 6 N 10 9
Output:
3 1 2
7 9 7 8 8 6 9 10
Explanation:
Testcase 1: Given tree is
3
/ \
2 1
Hence the zigzag traversal will be 3 1 2.
Testcase 2: Given tree is
7
/ \
7 9
/ \ / \
8 8 6 N
/ \
10 9
Hence the zigzag traversal will be 7 9 7 8 8 6 9 10., I have written this Solution Code: static ArrayList<Integer> list = new ArrayList<>();
static ArrayList<Integer> zigZagTraversal(Node root)
{
list = new ArrayList<>();
if(root==null)
return list;
Stack<Node>s1=new Stack<Node>();
Stack<Node>s2=new Stack<Node>();
s1.push(root);
while(s1.empty()==false || s2.empty()==false)
{
while(s1.empty()==false)
{
Node p=s1.pop();
list.add(p.data);
if(p.left!=null)
s2.push(p.left);
if(p.right!=null)
s2.push(p.right);
}
while(s2.empty()==false)
{
Node p=s2.pop();
list.add(p.data);
if(p.right!=null)
s1.push(p.right);
if(p.left!=null)
s1.push(p.left);
}
}
return list;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two positive integers N and M. Your task is to print first <b>M Special GCD numbers</b> which are greater than N.
<b>M Special GCD numbers</b> : First M numbers which are greater than N and whose GCD with N is equal to the smallest prime factor of N.User Task:
Since this is a functional problem, you don’t have to worry about the input, you just have to complete the function <b>printM_SpecialGCD()</b>, where you will get N and M as a parameter.
Constraints:
2 <= N <= 10^6
1 <= M <= 10^5Print the required answers separated by space.Sample Input:-
10 2
Sample Output:-
12 14
Explanation:-least prime divisor of 10 is 2.
Numbers greater than 10 whose gcd with 10 is equal to 2 are :- 12 14 16 18 22 . . . .
First two numbers of this series are:- 12 and 14
Sample Input:-
9 3
Sample Output:-
12 15 21, I have written this Solution Code: def GCD(x, y):
while(y):
x, y = y, x % y
return x
def primefactor(N) :
if N%2==0:
return 2
i = 3
while(i<=math.sqrt(N)):
if(N%i==0):
return i;
i=i+2;
return N;
def printM_SpecialGCD(N,M) :
prime=primefactor(N)
i=prime
count=0
while count!=M :
res=GCD(N,N+i)
if(res == prime):
count=count+1
print(N+i, end =" "),
i=i+prime
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two positive integers N and M. Your task is to print first <b>M Special GCD numbers</b> which are greater than N.
<b>M Special GCD numbers</b> : First M numbers which are greater than N and whose GCD with N is equal to the smallest prime factor of N.User Task:
Since this is a functional problem, you don’t have to worry about the input, you just have to complete the function <b>printM_SpecialGCD()</b>, where you will get N and M as a parameter.
Constraints:
2 <= N <= 10^6
1 <= M <= 10^5Print the required answers separated by space.Sample Input:-
10 2
Sample Output:-
12 14
Explanation:-least prime divisor of 10 is 2.
Numbers greater than 10 whose gcd with 10 is equal to 2 are :- 12 14 16 18 22 . . . .
First two numbers of this series are:- 12 and 14
Sample Input:-
9 3
Sample Output:-
12 15 21, I have written this Solution Code:
int gcd(int a,int b){
int temp = 0;
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
int primeFactors(int n)
{
int m=0;
// Print the number of 2s that divide n
if (n%2==0)
{
m= 2;
return m;
}
for (int i = 3; i <= sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
if (n%i == 0)
{
m=i;
return m;
}
}
if(n>2) {
m=n;
}
return m;
}
void printM_SpecialGCD(int N, int M)
{
int prime = primeFactors(N);
int count =0;
int i=prime;
while(count!=M){
int res = gcd(N,N+i);
if(res==prime){
cout<<N+i<<" ";
count++;
}
i+=prime;
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two positive integers N and M. Your task is to print first <b>M Special GCD numbers</b> which are greater than N.
<b>M Special GCD numbers</b> : First M numbers which are greater than N and whose GCD with N is equal to the smallest prime factor of N.User Task:
Since this is a functional problem, you don’t have to worry about the input, you just have to complete the function <b>printM_SpecialGCD()</b>, where you will get N and M as a parameter.
Constraints:
2 <= N <= 10^6
1 <= M <= 10^5Print the required answers separated by space.Sample Input:-
10 2
Sample Output:-
12 14
Explanation:-least prime divisor of 10 is 2.
Numbers greater than 10 whose gcd with 10 is equal to 2 are :- 12 14 16 18 22 . . . .
First two numbers of this series are:- 12 and 14
Sample Input:-
9 3
Sample Output:-
12 15 21, I have written this Solution Code:
static void printM_SpecialGCD(int N, int M)
{
int prime = primeFactors(N);
int count =0;
int i=prime;
while(count!=M){
int res = gcd(N,N+i);
if(res==prime){
System.out.print(N+i + " ");
count++;
}
i+=prime;
}
}
public static int primeFactors(int n)
{
int m=0;
// Print the number of 2s that divide n
if (n%2==0)
{
m= 2;
return m;
}
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
if (n%i == 0)
{
m=i;
return m;
}
}
if(n>2) {
m=n;
}
return m;
}
public static int gcd(int a,int b){
int temp = 0;
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two positive integers N and M. Your task is to print first <b>M Special GCD numbers</b> which are greater than N.
<b>M Special GCD numbers</b> : First M numbers which are greater than N and whose GCD with N is equal to the smallest prime factor of N.User Task:
Since this is a functional problem, you don’t have to worry about the input, you just have to complete the function <b>printM_SpecialGCD()</b>, where you will get N and M as a parameter.
Constraints:
2 <= N <= 10^6
1 <= M <= 10^5Print the required answers separated by space.Sample Input:-
10 2
Sample Output:-
12 14
Explanation:-least prime divisor of 10 is 2.
Numbers greater than 10 whose gcd with 10 is equal to 2 are :- 12 14 16 18 22 . . . .
First two numbers of this series are:- 12 and 14
Sample Input:-
9 3
Sample Output:-
12 15 21, I have written this Solution Code: int gcd(int a,int b){
int temp = 0;
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
int primeFactors(int n)
{
int m=0;
// Print the number of 2s that divide n
if (n%2==0)
{
m= 2;
return m;
}
int c =sqrt(n);
for (int i = 3; i <= c; i+= 2)
{
// While i divides n, print i and divide n
if (n%i == 0)
{
m=i;
return m;
}
}
if(n>2) {
m=n;
}
return m;
}
void printM_SpecialGCD(int N, int M)
{
int prime = primeFactors(N);
int count =0;
int i=prime;
while(count!=M){
int res = gcd(N,N+i);
if(res==prime){
printf("%d ",N+i);
count++;
}
i+=prime;
}
}, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array arr[] of N integers in which elements may be repeating several times. Also, a positive number K is given and the task is to find sum of total frequencies of K most occurring elements
Note: The value of K is guaranteed to be less than or equal to the number of distinct elements in arr.First line of input contains number of testcases T. For each testcase, first line of input contains the size of array N, and next line contains N positive integers. The last line contains K.
Constraints:
1 <= T <= 100
1 <= K <= N
1 <= N <= 10^4
1 <= arr[i] <= 10^6For each testcase, print the sum of total frequencies of K most occurring elements in the given array.Sample Input:
2
8
3 1 4 4 5 2 6 1
2
8
3 3 3 4 1 1 6 1
2
Sample Output:
4
6
Explanation:
Testcase 1: Since, 4 and 1 are 2 most occurring elements in the array with their frequencies as 2, 2. So total frequency is 2 + 2 = 4.
Testcase 2: Since, 3 and 1 are most occurring elements in the array with frequencies 3, 3 respectively. So, total frequency is 6., I have written this Solution Code: import java.util.*;
import java.io.*;
class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
} else {
continue;
}
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
class Main {
private static long solve(Reader sc,int n) throws IOException {
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
int key = sc.nextInt();
map.put(key, map.getOrDefault(key, 0)+1);
}
int limt = sc.nextInt();
PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());
for (Integer integer : map.keySet()) {
queue.add(map.get(integer));
}
long ans = 0;
while (limt-->0) {
ans += queue.poll();
}
return ans;
}
public static void main(String[] args) throws IOException {
Reader sc = new Reader();
int t = sc.nextInt();
while (t-->0) {
int n = sc.nextInt();
System.out.println(solve(sc, n));
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array arr[] of N integers in which elements may be repeating several times. Also, a positive number K is given and the task is to find sum of total frequencies of K most occurring elements
Note: The value of K is guaranteed to be less than or equal to the number of distinct elements in arr.First line of input contains number of testcases T. For each testcase, first line of input contains the size of array N, and next line contains N positive integers. The last line contains K.
Constraints:
1 <= T <= 100
1 <= K <= N
1 <= N <= 10^4
1 <= arr[i] <= 10^6For each testcase, print the sum of total frequencies of K most occurring elements in the given array.Sample Input:
2
8
3 1 4 4 5 2 6 1
2
8
3 3 3 4 1 1 6 1
2
Sample Output:
4
6
Explanation:
Testcase 1: Since, 4 and 1 are 2 most occurring elements in the array with their frequencies as 2, 2. So total frequency is 2 + 2 = 4.
Testcase 2: Since, 3 and 1 are most occurring elements in the array with frequencies 3, 3 respectively. So, total frequency is 6., I have written this Solution Code: t=int(input())
for m in range(0,t):
n=int(input())
arr=input().split()
k=int(input())
hm={}
for i in range(0,n):
arr[i]=int(arr[i])
if(arr[i] not in hm):
hm[arr[i]]=1
else:
hm[arr[i]]+=1
s=0
ans=sorted(list(hm.values()))
print (sum(ans[len(ans)-k:len(ans)])), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array arr[] of N integers in which elements may be repeating several times. Also, a positive number K is given and the task is to find sum of total frequencies of K most occurring elements
Note: The value of K is guaranteed to be less than or equal to the number of distinct elements in arr.First line of input contains number of testcases T. For each testcase, first line of input contains the size of array N, and next line contains N positive integers. The last line contains K.
Constraints:
1 <= T <= 100
1 <= K <= N
1 <= N <= 10^4
1 <= arr[i] <= 10^6For each testcase, print the sum of total frequencies of K most occurring elements in the given array.Sample Input:
2
8
3 1 4 4 5 2 6 1
2
8
3 3 3 4 1 1 6 1
2
Sample Output:
4
6
Explanation:
Testcase 1: Since, 4 and 1 are 2 most occurring elements in the array with their frequencies as 2, 2. So total frequency is 2 + 2 = 4.
Testcase 2: Since, 3 and 1 are most occurring elements in the array with frequencies 3, 3 respectively. So, total frequency is 6., I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> v;
unordered_map<long,int> m;
long x;
for(int i=0;i<n;i++){
cin>>x;
m[x]++;
}
int k;
cin>>k;
for(auto it=m.begin();it!=m.end();it++){
v.emplace_back(it->second);
}
sort(v.begin(),v.end());
int ans=0;
for(int i=v.size()-1;i>=(v.size()-k);i--){
ans+=v[i];
}
cout<<ans<<endl;}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a list of employee names. You need to search if a given person exists in the employee list or not?First line contains a single integer n denoting number of employees.
Next n line contains name of each employee.
Next line contains a single name.
<b>Constraints</b>
1 ≤ n ≤ 10<sup>5</sup>
1 ≤ length of names ≤ 20
name is made of only lowercase English letters.Output "YES" if given person exist in employee list else print "NO".Example :
4
jace
luke
deamon
aemond
luke
Output:
YES
Explanation:
employees : [ jace, luke, deamon, aemond ]
person : luke
luke exists in employee list., I have written this Solution Code: import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
int n=Integer.parseInt(in.next());
HashMap<String,Integer> emp = new HashMap<>();
for(int i=0;i<n;i++){
String s=in.next();
emp.put(s,1);
}
String name = in.next();
if(emp.containsKey(name)){
out.print("YES");
}
else out.print("NO");
out.close();
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an undirected graph, the task is to detect if there is a cycle in the undirected graph or not.The first line of input contains two integers N and M which denotes the no of vertices and no of edges in the graph respectively.
Next M lines contain space-separated integers u and v denoting that there is a directed edge from u to v.
Constraints:
1 <= N, M <= 1000
0 <= u, v <= N-1, u != v
There are no self loops or multiple edges.
Print 'Yes' if there is a cycle in the graph otherwise print 'No'Sample Input 1:
4 5
0 1
1 2
2 3
3 0
0 2
Sample Output 1:
Yes
Explanation:
There is a cycle with nodes 0, 1, 2, 3
Sample Input 2:
4 3
0 1
1 2
2 3
Sample Output 2:
No
Explanation:
There is no cycle in this graph, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
static ArrayList<Integer> ar[];
static boolean st[];
static boolean status=false;
public static void main (String[] args) throws Exception {
BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));
try{
String sa[]=rd.readLine().split(" ");
int n=Integer.parseInt(sa[0]);
int e=Integer.parseInt(sa[1]);
st=new boolean[n+1];
ar=new ArrayList[n+1];
for(int i=0;i<n;i++)
ar[i]=new ArrayList<Integer>();
for(int i=0;i<e;i++)
{
sa=rd.readLine().split(" ");
int u=Integer.parseInt(sa[0]);;
int v=Integer.parseInt(sa[1]);;
ar[u].add(v);
ar[v].add(u);
}
dfs(0);
if(status)
System.out.println("Yes");
else
System.out.println("No");
}
catch(Exception e)
{
if(status)
System.out.println("Yes");
else
System.out.println("Yes");
}
}
static int p=-1;
static void dfs(int k)
{
try{
Stack <Integer> st1=new Stack<>();
int l=0;
st1.add(k);
while(!st1.empty())
{
if(!st1.empty())
l=st1.pop();
if(st[l])
{
status=true;
return;
}
st[l]=true;
for(int i=0;i<ar[l].size();i++)
{
if(!st[ar[l].get(i)])
st1.push(ar[l].get(i));
}
}
}
catch(Exception e)
{
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an undirected graph, the task is to detect if there is a cycle in the undirected graph or not.The first line of input contains two integers N and M which denotes the no of vertices and no of edges in the graph respectively.
Next M lines contain space-separated integers u and v denoting that there is a directed edge from u to v.
Constraints:
1 <= N, M <= 1000
0 <= u, v <= N-1, u != v
There are no self loops or multiple edges.
Print 'Yes' if there is a cycle in the graph otherwise print 'No'Sample Input 1:
4 5
0 1
1 2
2 3
3 0
0 2
Sample Output 1:
Yes
Explanation:
There is a cycle with nodes 0, 1, 2, 3
Sample Input 2:
4 3
0 1
1 2
2 3
Sample Output 2:
No
Explanation:
There is no cycle in this graph, I have written this Solution Code:
def dfs(adjList,vis,start,prev):
vis[start]=True
for i in adjList[start]:
if i == prev:
continue
if vis[i]:
return True
else:
dfs(adjList,vis,i,start)
return False
np=list(map(int,input().rstrip().split()))
n=np[0]
e=np[1]
adjList = [[] for i in range(n+1)]
for i in range(e):
edge = list(map(int,input().rstrip().split()))
adjList[edge[0]].append(edge[1])
adjList[edge[1]].append(edge[0])
vis = [False for i in range(n+1)]
flag=0
for i in range(n):
if not vis[i]:
if dfs(adjList,vis,i,0):
flag=1
break
if flag:
print("Yes")
else:
print("No"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an undirected graph, the task is to detect if there is a cycle in the undirected graph or not.The first line of input contains two integers N and M which denotes the no of vertices and no of edges in the graph respectively.
Next M lines contain space-separated integers u and v denoting that there is a directed edge from u to v.
Constraints:
1 <= N, M <= 1000
0 <= u, v <= N-1, u != v
There are no self loops or multiple edges.
Print 'Yes' if there is a cycle in the graph otherwise print 'No'Sample Input 1:
4 5
0 1
1 2
2 3
3 0
0 2
Sample Output 1:
Yes
Explanation:
There is a cycle with nodes 0, 1, 2, 3
Sample Input 2:
4 3
0 1
1 2
2 3
Sample Output 2:
No
Explanation:
There is no cycle in this graph, I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
vector<int> g[N];
int vis[N];
bool flag = 0;
void dfs(int u, int p){
vis[u] = 1;
for(auto i: g[u]){
if(i == p) continue;
if(vis[i] == 1)
flag = 1;
if(vis[i] == 0) dfs(i, u);
}
vis[u] = 2;
}
signed main() {
IOS;
int n, m;
cin >> n >> m;
for(int i = 1; i <= m; i++){
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
for(int i = 0; i < n; i++){
if(vis[i]) continue;
dfs(i, n);
}
if(flag)
cout << "Yes";
else
cout << "No";
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a 2d matrix of size M*N, print the zig traversal of the matrix as shown:-
Consider a matrix of size 5*4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
ZigZag traversal:-
1
5 2
9 6 3
13 10 7 4
17 14 11 8
18 15 12
19 16
20First line of input contains two integers M and N. Next M lines contains N space- separated integers each.
Constraints:-
1 <= M, N <= 100
1 <= Matrix[i][j] <= 100000Print the zig- zag traversal of the matrix as shown.Sample Input:-
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Sample Output:-
1
4 2
7 5 3
10 8 6
11 9
12, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main (String[] args)throws Exception {
Reader sc=new Reader();
int m =sc.nextInt();
int n=sc.nextInt();
int [][]M=new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
M[i][j]=sc.nextInt();
}
}
int i,j;
for(int k=0;k<m-1;k++){
i=k;
j=0;
while(i>=0 && j < n){
System.out.print(M[i][j]+" ");
i=i-1;
j=j+1;
}
System.out.println("");
}
for(int k=0;k<n;k++){
i=m-1;
j=k;
while(j<=n-1 && i >= 0){
System.out.print(M[i][j]+" ");
i=i-1;
j=j+1;
}
System.out.println("");
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a 2d matrix of size M*N, print the zig traversal of the matrix as shown:-
Consider a matrix of size 5*4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
ZigZag traversal:-
1
5 2
9 6 3
13 10 7 4
17 14 11 8
18 15 12
19 16
20First line of input contains two integers M and N. Next M lines contains N space- separated integers each.
Constraints:-
1 <= M, N <= 100
1 <= Matrix[i][j] <= 100000Print the zig- zag traversal of the matrix as shown.Sample Input:-
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Sample Output:-
1
4 2
7 5 3
10 8 6
11 9
12, I have written this Solution Code: M, N = [int(x) for x in input().split()]
mat = []
for i in range(M):
single_row = list(map(int, input().split()))
mat.append(single_row)
def diagonalOrder(arr, n, m):
ans = [[] for i in range(n + m - 1)]
for i in range(m):
for j in range(n):
ans[i + j].append(arr[j][i])
for i in range(len(ans)):
for j in range(len(ans[i])):
print(ans[i][j], end = " ")
print()
diagonalOrder(mat, M, N), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a 2d matrix of size M*N, print the zig traversal of the matrix as shown:-
Consider a matrix of size 5*4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
ZigZag traversal:-
1
5 2
9 6 3
13 10 7 4
17 14 11 8
18 15 12
19 16
20First line of input contains two integers M and N. Next M lines contains N space- separated integers each.
Constraints:-
1 <= M, N <= 100
1 <= Matrix[i][j] <= 100000Print the zig- zag traversal of the matrix as shown.Sample Input:-
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Sample Output:-
1
4 2
7 5 3
10 8 6
11 9
12, I have written this Solution Code:
#include <bits/stdc++.h>
using namespace std;
#define MEM(a, b) memset(a, (b), sizeof(a))
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define IN(A, B, C) assert( B <= A && A <= C)
#define MP make_pair
#define FOR(i,a) for(int i=0;i<a;i++)
#define FOR1(i,j,a) for(int i=j;i<a;i++)
#define EB emplace_back
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
#define max1 1001
#define MOD 1000000007
#define read(type) readInt<type>()
#define out(x) cout<<x<<'\n'
#define out1(x) cout<<x<<" "
#define END cout<<'\n'
#define int long long
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(), (v).end()
void fast(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int a[max1][max1];
signed main(){
int m,n;
cin>>m>>n;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cin>>a[i][j];
}
}
for(int i=0;i<m;i++){
for(int j=i;j>=0;j--){
if((i-j)>=n){break;}
cout<<a[j][i-j]<<" ";
}
cout<<endl;
}
for(int i=1;i<n;i++){
for(int j=m-1;j>=0;j--){
if((i+m-1-j)>=n){break;}
cout<<a[j][i+(m-1-j)]<<" ";
}
cout<<endl;
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara is trying a new magic trick on you, The magic trick goes in 6 steps:-
1. Think of a number X(don't tell Sara)
2. Add A(Given by Sara) to it.
3. Double the sum in your mind.
4. Add an even number B(Given by Sara) to it.
5. Half the amount
6. Subtract the initial number which you had taken from the sum
After this Sara will tell the resulting amount without knowing the initial number, can you print the result for her?
<b>Note: B is always even. </b>You don't have to worry about the input, you just have to complete the function <b>magicTrick()</b>
<b>Constraints</b>:-
1 <= A, B <= 1000Print the resulting amountSample Input:-
3 4
Sample Output:-
5
Sample Input:-
8 4
Sample Output:-
10, I have written this Solution Code: void magicTrick(int a, int b){
cout<<a+b/2;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara is trying a new magic trick on you, The magic trick goes in 6 steps:-
1. Think of a number X(don't tell Sara)
2. Add A(Given by Sara) to it.
3. Double the sum in your mind.
4. Add an even number B(Given by Sara) to it.
5. Half the amount
6. Subtract the initial number which you had taken from the sum
After this Sara will tell the resulting amount without knowing the initial number, can you print the result for her?
<b>Note: B is always even. </b>You don't have to worry about the input, you just have to complete the function <b>magicTrick()</b>
<b>Constraints</b>:-
1 <= A, B <= 1000Print the resulting amountSample Input:-
3 4
Sample Output:-
5
Sample Input:-
8 4
Sample Output:-
10, I have written this Solution Code: static void magicTrick(int a, int b){
System.out.println(a + b/2);
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara is trying a new magic trick on you, The magic trick goes in 6 steps:-
1. Think of a number X(don't tell Sara)
2. Add A(Given by Sara) to it.
3. Double the sum in your mind.
4. Add an even number B(Given by Sara) to it.
5. Half the amount
6. Subtract the initial number which you had taken from the sum
After this Sara will tell the resulting amount without knowing the initial number, can you print the result for her?
<b>Note: B is always even. </b>You don't have to worry about the input, you just have to complete the function <b>magicTrick()</b>
<b>Constraints</b>:-
1 <= A, B <= 1000Print the resulting amountSample Input:-
3 4
Sample Output:-
5
Sample Input:-
8 4
Sample Output:-
10, I have written this Solution Code: A,B = map(int,input().split(' '))
C = A+B//2
print(C)
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number N and a number P, your task is to calculate N<sup>P</sup>. Since the ans can be very long calculate your ans as N<sup>P</sup>%M where M = 10<sup>9</sup>+7Input contains only two integers N and P separated by spaces.
Constraints:-
1 < = N, P <= 1000000000Print N<sup>P</sup>%M.Sample Input:-
2 5
Sample Output:-
32
Sample Input:-
2 100
Sample Output:-
976371285, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException{
BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));
String y[]=rd.readLine().split(" ");
long n=Long.parseLong(y[0]);
long p=Long.parseLong(y[1]);
long v=1;
while(p>0){
if((p&1L)==1L)
v=(v*n)%1000000007;
p/=2;
n=(n*n)%1000000007;
}
System.out.print(v);
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number N and a number P, your task is to calculate N<sup>P</sup>. Since the ans can be very long calculate your ans as N<sup>P</sup>%M where M = 10<sup>9</sup>+7Input contains only two integers N and P separated by spaces.
Constraints:-
1 < = N, P <= 1000000000Print N<sup>P</sup>%M.Sample Input:-
2 5
Sample Output:-
32
Sample Input:-
2 100
Sample Output:-
976371285, I have written this Solution Code: n, p =input().split()
n, p =int(n), int(p)
def FastModularExponentiation(b, k, m):
res = 1
b = b % m
while (k > 0):
if ((k & 1) == 1):
res = (res * b) % m
k = k >> 1
b = (b * b) % m
return res
m=pow(10,9)+7
print(FastModularExponentiation(n, p, m)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number N and a number P, your task is to calculate N<sup>P</sup>. Since the ans can be very long calculate your ans as N<sup>P</sup>%M where M = 10<sup>9</sup>+7Input contains only two integers N and P separated by spaces.
Constraints:-
1 < = N, P <= 1000000000Print N<sup>P</sup>%M.Sample Input:-
2 5
Sample Output:-
32
Sample Input:-
2 100
Sample Output:-
976371285, I have written this Solution Code:
// author-Shivam gupta
#include <bits/stdc++.h>
using namespace std;
#define MEM(a, b) memset(a, (b), sizeof(a))
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define IN(A, B, C) assert( B <= A && A <= C)
#define MP make_pair
#define FOR(i,a) for(int i=0;i<a;i++)
#define FOR1(i,j,a) for(int i=j;i<a;i++)
#define EB emplace_back
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
#define read(type) readInt<type>()
#define max1 100001
#define out(x) cout<<x<<'\n'
#define out1(x) cout<<x<<" "
#define END cout<<'\n'
#define int long long
void fast(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int power(int x, unsigned int y, int p)
{
int res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0) return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1)
res = (res*x) % p;
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % p;
}
return res;
}
// Driver code
signed main()
{
int x ;
int y;
cin>>x>>y;
int p = 1e9+7;
cout<< power(x, y, p);
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara is trying a new type of game in which she can jump in either the left direction or in the right direction. Also after each jump the range of her jump increases by 1 unit. i.e if starts from 1 in the next jump she has to jump 2 units then 3 units and so on.
Given the number of jumps as N, the range of the first jump to be 1. What will be the minimum distance Sara can be at from the starting point.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>minDistanceCoveredBySara()</b> that takes integer N as an argument.
Constraints:-
1 <= N <= 1000Return the minimum distance Sara can be at from the starting point.Sample Input:-
3
Sample Output:-
0
Explanation:-
First jump:- right
Second jump:- right
Third jump:- left
Total distance covered = 1+2-3 = 0
Sample Input:-
5
Sample Output:-
1, I have written this Solution Code: int minDistanceCoveredBySara(int N){
if(N%4==1 || N%4==2){return 1;}
return 0;
}
, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara is trying a new type of game in which she can jump in either the left direction or in the right direction. Also after each jump the range of her jump increases by 1 unit. i.e if starts from 1 in the next jump she has to jump 2 units then 3 units and so on.
Given the number of jumps as N, the range of the first jump to be 1. What will be the minimum distance Sara can be at from the starting point.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>minDistanceCoveredBySara()</b> that takes integer N as an argument.
Constraints:-
1 <= N <= 1000Return the minimum distance Sara can be at from the starting point.Sample Input:-
3
Sample Output:-
0
Explanation:-
First jump:- right
Second jump:- right
Third jump:- left
Total distance covered = 1+2-3 = 0
Sample Input:-
5
Sample Output:-
1, I have written this Solution Code: int minDistanceCoveredBySara(int N){
if(N%4==1 || N%4==2){return 1;}
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara is trying a new type of game in which she can jump in either the left direction or in the right direction. Also after each jump the range of her jump increases by 1 unit. i.e if starts from 1 in the next jump she has to jump 2 units then 3 units and so on.
Given the number of jumps as N, the range of the first jump to be 1. What will be the minimum distance Sara can be at from the starting point.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>minDistanceCoveredBySara()</b> that takes integer N as an argument.
Constraints:-
1 <= N <= 1000Return the minimum distance Sara can be at from the starting point.Sample Input:-
3
Sample Output:-
0
Explanation:-
First jump:- right
Second jump:- right
Third jump:- left
Total distance covered = 1+2-3 = 0
Sample Input:-
5
Sample Output:-
1, I have written this Solution Code: def minDistanceCoveredBySara(N):
if N%4==1 or N%4==2:
return 1
return 0
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sara is trying a new type of game in which she can jump in either the left direction or in the right direction. Also after each jump the range of her jump increases by 1 unit. i.e if starts from 1 in the next jump she has to jump 2 units then 3 units and so on.
Given the number of jumps as N, the range of the first jump to be 1. What will be the minimum distance Sara can be at from the starting point.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>minDistanceCoveredBySara()</b> that takes integer N as an argument.
Constraints:-
1 <= N <= 1000Return the minimum distance Sara can be at from the starting point.Sample Input:-
3
Sample Output:-
0
Explanation:-
First jump:- right
Second jump:- right
Third jump:- left
Total distance covered = 1+2-3 = 0
Sample Input:-
5
Sample Output:-
1, I have written this Solution Code: static int minDistanceCoveredBySara(int N){
if(N%4==1 || N%4==2){return 1;}
return 0;
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Ronaldo has challenged Messi to beat his team in the upcoming “Friendly” fixture. But both these legends are tired of the original football rules, so they decided to play Football with a twist. Each player is assigned an ID, from 1 to 10^6. Initially Ronaldo has the ball in his posession. Given a sequence of N passes, help Messi Know which ID player has the ball, after N passes.
Note: Passes are of two types :
i) P ID, which means the player currently having the ball passes it to Player with identity ID.
ii) B, which means the player currently having the ball passes it back to the Player he got the Pass From.
Also, It is guaranteed that the given order of passes will be a valid order.The first line of input contains number of testcases T. The 1st line of each testcase, contains two integers, N and ID1, denoting the total number of passes and the ID of Ronaldo. Respectively. Each of the next N lines, contains the information of a Pass which can be either of the above two types, i.e:
1) P ID
2) B
Constraints
1 <= T <= 100
1 <= N <= 10^5
1 <= IDs <= 10^6
Sum of N for every test case is less than 10^6For each testcase you need to print the ID of the Player having the ball after N passes.Input :
2
3 1
P 13
P 14
B
5 1
P 12
P 13
P 14
B
B
Output :
13
14
Explanation :
Testcase 1: Initially, the ball is with Ronaldo, having ID 1.
In the first pass, he passes the ball to Player with ID 13.
In the Second Pass, the player currently having the ball, ie Player with ID 13, passes it to player with ID 14.
In the last pass the player currently having the ball, ie Player with ID 14 passed the ball back to the player from whom he got the Pass, i.e the ball is passed back to Player with Player ID 13, as Player ID 13 had passed the ball to player ID 14 in the previous pass.
Testcase 2: Initially, the ball is with Ronaldo, having ID 1.
In the first pass he passes the ball to player with ID 12.
In the second pass, the second player passes the ball to palyer with ID 13, again the player with ID 13 passes the ball to player with ID 14.
Now, player with ID 14 passed back the ball to 13, and again 13 passes back the ball to 14., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
while (t-- > 0) {
String[] line = br.readLine().trim().split(" ");
int n = Integer.parseInt(line[0]);
int curr = Integer.parseInt(line[1]);
int prev = curr;
while (n-- > 0) {
String[] currLine = br.readLine().trim().split(" ");
if (currLine[0].equals("P")) {
prev = curr;
curr = Integer.parseInt(currLine[1]);
}
if (currLine[0].equals("B")) {
int temp = curr;
curr = prev;
prev = temp;
}
}
System.out.println(curr);
System.gc();
}
br.close();
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Ronaldo has challenged Messi to beat his team in the upcoming “Friendly” fixture. But both these legends are tired of the original football rules, so they decided to play Football with a twist. Each player is assigned an ID, from 1 to 10^6. Initially Ronaldo has the ball in his posession. Given a sequence of N passes, help Messi Know which ID player has the ball, after N passes.
Note: Passes are of two types :
i) P ID, which means the player currently having the ball passes it to Player with identity ID.
ii) B, which means the player currently having the ball passes it back to the Player he got the Pass From.
Also, It is guaranteed that the given order of passes will be a valid order.The first line of input contains number of testcases T. The 1st line of each testcase, contains two integers, N and ID1, denoting the total number of passes and the ID of Ronaldo. Respectively. Each of the next N lines, contains the information of a Pass which can be either of the above two types, i.e:
1) P ID
2) B
Constraints
1 <= T <= 100
1 <= N <= 10^5
1 <= IDs <= 10^6
Sum of N for every test case is less than 10^6For each testcase you need to print the ID of the Player having the ball after N passes.Input :
2
3 1
P 13
P 14
B
5 1
P 12
P 13
P 14
B
B
Output :
13
14
Explanation :
Testcase 1: Initially, the ball is with Ronaldo, having ID 1.
In the first pass, he passes the ball to Player with ID 13.
In the Second Pass, the player currently having the ball, ie Player with ID 13, passes it to player with ID 14.
In the last pass the player currently having the ball, ie Player with ID 14 passed the ball back to the player from whom he got the Pass, i.e the ball is passed back to Player with Player ID 13, as Player ID 13 had passed the ball to player ID 14 in the previous pass.
Testcase 2: Initially, the ball is with Ronaldo, having ID 1.
In the first pass he passes the ball to player with ID 12.
In the second pass, the second player passes the ball to palyer with ID 13, again the player with ID 13 passes the ball to player with ID 14.
Now, player with ID 14 passed back the ball to 13, and again 13 passes back the ball to 14., I have written this Solution Code: for i in range(int(input())):
N, ID = map(int,input().split())
pre = 0
for i in range(N):
arr = input().split()
if len(arr)==2:
pre,ID = ID,arr[1]
else:
ID,pre = pre,ID
print(ID) if pre else print(0), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Ronaldo has challenged Messi to beat his team in the upcoming “Friendly” fixture. But both these legends are tired of the original football rules, so they decided to play Football with a twist. Each player is assigned an ID, from 1 to 10^6. Initially Ronaldo has the ball in his posession. Given a sequence of N passes, help Messi Know which ID player has the ball, after N passes.
Note: Passes are of two types :
i) P ID, which means the player currently having the ball passes it to Player with identity ID.
ii) B, which means the player currently having the ball passes it back to the Player he got the Pass From.
Also, It is guaranteed that the given order of passes will be a valid order.The first line of input contains number of testcases T. The 1st line of each testcase, contains two integers, N and ID1, denoting the total number of passes and the ID of Ronaldo. Respectively. Each of the next N lines, contains the information of a Pass which can be either of the above two types, i.e:
1) P ID
2) B
Constraints
1 <= T <= 100
1 <= N <= 10^5
1 <= IDs <= 10^6
Sum of N for every test case is less than 10^6For each testcase you need to print the ID of the Player having the ball after N passes.Input :
2
3 1
P 13
P 14
B
5 1
P 12
P 13
P 14
B
B
Output :
13
14
Explanation :
Testcase 1: Initially, the ball is with Ronaldo, having ID 1.
In the first pass, he passes the ball to Player with ID 13.
In the Second Pass, the player currently having the ball, ie Player with ID 13, passes it to player with ID 14.
In the last pass the player currently having the ball, ie Player with ID 14 passed the ball back to the player from whom he got the Pass, i.e the ball is passed back to Player with Player ID 13, as Player ID 13 had passed the ball to player ID 14 in the previous pass.
Testcase 2: Initially, the ball is with Ronaldo, having ID 1.
In the first pass he passes the ball to player with ID 12.
In the second pass, the second player passes the ball to palyer with ID 13, again the player with ID 13 passes the ball to player with ID 14.
Now, player with ID 14 passed back the ball to 13, and again 13 passes back the ball to 14., I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
signed main() {
IOS;
int t; cin >> t;
while(t--){
int n, id; cin >> n >> id;
int pre = 0, cur = id;
for(int i = 1; i <= n; i++){
char c; cin >> c;
if(c == 'P'){
int x; cin >> x;
pre = cur;
cur = x;
}
else{
swap(pre, cur);
}
}
cout << cur << endl;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There are n ropes, you need to cut k pieces of the same length from them. Find the maximum length of the piece you can get.The first line of the input contains two integers n and k.
Next n lines contain one number each, the length of the rope a<sub>i</sub>.
<b>Constraints</b>
1 ≤ n, k ≤ 10000
1 ≤ a<sub>i</sub> ≤ 10<sup>7</sup>Print one real number maximum length of the piece you can get. Print the result up to 6 decimal places.Sample Input
4 11
802
743
457
539
Sample Output
200.500000, I have written this Solution Code: #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template <class T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class key, class value, class cmp = std::less<key>>
using ordered_map = tree<key, value, cmp, rb_tree_tag, tree_order_statistics_node_update>;
// find_by_order(k) returns iterator to kth element starting from 0;
// order_of_key(k) returns count of elements strictly smaller than k;
#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 2351
#endif
#define int long long
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
inline int64_t random_long(int l = LLONG_MIN, int r = LLONG_MAX) {
uniform_int_distribution<int64_t> generator(l, r);
return generator(rng);
}
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
auto start = std::chrono::high_resolution_clock::now();
int n, k;
cin >> n >> k;
vector<double> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
double l = 0, r = 1e9;
auto check = [&](double x) -> bool {
int piece = 0;
for (int i = 0; i < n; i++) {
piece += a[i] / x;
}
if (piece >= k) {
return true;
}
return false;
};
while (r - l > 0.000001) {
double mid = l + (r - l) / 2;
if (check(mid))
l = mid;
else
r = mid;
}
printf("%0.6f", l);
return 0;
};
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N numbers are arranged in Circle. Find the Sum of all K contiguous Sub-arrays.The first line of the input contains an integer N, the length of the array, and K. The next line contains N integers which are elements of the array.
<b>User task:</b> Since this is a functional problem you don't have to worry about the input. You just have to complete the function kCircleSum(arr, N, K) which contains arr(array) and N(size of the array), and K as a parameter
<b>Constraints</b>
1 <= N <= 100000
1 <= arr[I] <= 100000
1 <= K <= NYou need to print N space-separated integers ith integer denoting Sum of sub-array of length K starting at index i.Sample Input
3 1
1 2 3
Sample Output
1 2 3
Explanation : k=1 so ans is 1, 2, and 3.
Sample Input
5 2
6 4 3 4 1
Sample Output
10 7 7 5 7, I have written this Solution Code: void kCircleSum(int arr[],int n,int k){
long long ans=0;
for(int i=0;i<k;i++){
ans+=arr[i];
}
for(int i=0;i<n;i++){
printf("%lli ",ans);
ans+=arr[(i+k)%n]-arr[i];
}
}, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N numbers are arranged in Circle. Find the Sum of all K contiguous Sub-arrays.The first line of the input contains an integer N, the length of the array, and K. The next line contains N integers which are elements of the array.
<b>User task:</b> Since this is a functional problem you don't have to worry about the input. You just have to complete the function kCircleSum(arr, N, K) which contains arr(array) and N(size of the array), and K as a parameter
<b>Constraints</b>
1 <= N <= 100000
1 <= arr[I] <= 100000
1 <= K <= NYou need to print N space-separated integers ith integer denoting Sum of sub-array of length K starting at index i.Sample Input
3 1
1 2 3
Sample Output
1 2 3
Explanation : k=1 so ans is 1, 2, and 3.
Sample Input
5 2
6 4 3 4 1
Sample Output
10 7 7 5 7, I have written this Solution Code: function kCircleSum(arr, arrSize, k)
{
var list = new Array(2*arrSize + 5)
for(var i = 0; i < arrSize; i++)
{
list[i+1] = arr[i]
list[i+arrSize+1] = list[i+1]
}
for(var i = 0; i < 2*arrSize; i++)
dp[i] = 0
for(var i=1;i<=2*arrSize;i++)
{
dp[i] = dp[i-1]+list[i]
}
var ans = ""
for(var i = 1; i <= arrSize; i++)
{
ans += (dp[i+k-1]-dp[i-1]) + " "
}
console.log(ans)
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N numbers are arranged in Circle. Find the Sum of all K contiguous Sub-arrays.The first line of the input contains an integer N, the length of the array, and K. The next line contains N integers which are elements of the array.
<b>User task:</b> Since this is a functional problem you don't have to worry about the input. You just have to complete the function kCircleSum(arr, N, K) which contains arr(array) and N(size of the array), and K as a parameter
<b>Constraints</b>
1 <= N <= 100000
1 <= arr[I] <= 100000
1 <= K <= NYou need to print N space-separated integers ith integer denoting Sum of sub-array of length K starting at index i.Sample Input
3 1
1 2 3
Sample Output
1 2 3
Explanation : k=1 so ans is 1, 2, and 3.
Sample Input
5 2
6 4 3 4 1
Sample Output
10 7 7 5 7, I have written this Solution Code: static void kCircleSum(int arr[],int n,int k){
long ans=0;
for(int i=0;i<k;i++){
ans+=arr[i];
}
for(int i=0;i<n;i++){
System.out.print(ans+" ");
ans+=arr[(i+k)%n]-arr[i];
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N numbers are arranged in Circle. Find the Sum of all K contiguous Sub-arrays.The first line of the input contains an integer N, the length of the array, and K. The next line contains N integers which are elements of the array.
<b>User task:</b> Since this is a functional problem you don't have to worry about the input. You just have to complete the function kCircleSum(arr, N, K) which contains arr(array) and N(size of the array), and K as a parameter
<b>Constraints</b>
1 <= N <= 100000
1 <= arr[I] <= 100000
1 <= K <= NYou need to print N space-separated integers ith integer denoting Sum of sub-array of length K starting at index i.Sample Input
3 1
1 2 3
Sample Output
1 2 3
Explanation : k=1 so ans is 1, 2, and 3.
Sample Input
5 2
6 4 3 4 1
Sample Output
10 7 7 5 7, I have written this Solution Code: def kCircleSum(arr,n,k):
ans=0
for i in range (0,k):
ans=ans+arr[i]
for i in range (0,n):
print(ans,end=" ")
ans=ans+arr[int((i+k)%n)]-arr[i]
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N numbers are arranged in Circle. Find the Sum of all K contiguous Sub-arrays.The first line of the input contains an integer N, the length of the array, and K. The next line contains N integers which are elements of the array.
<b>User task:</b> Since this is a functional problem you don't have to worry about the input. You just have to complete the function kCircleSum(arr, N, K) which contains arr(array) and N(size of the array), and K as a parameter
<b>Constraints</b>
1 <= N <= 100000
1 <= arr[I] <= 100000
1 <= K <= NYou need to print N space-separated integers ith integer denoting Sum of sub-array of length K starting at index i.Sample Input
3 1
1 2 3
Sample Output
1 2 3
Explanation : k=1 so ans is 1, 2, and 3.
Sample Input
5 2
6 4 3 4 1
Sample Output
10 7 7 5 7, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
void kCircleSum(int arr[],int n,int k){
long long ans=0;
for(int i=0;i<k;i++){
ans+=arr[i];
}
for(int i=0;i<n;i++){
printf("%lli ",ans);
ans+=arr[(i+k)%n]-arr[i];
}
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array, your task is to print the minimum size of the set so that at least half of the integers of the array are removed.The first line contains n the size of the array and the next line contains input of the array
<b>Constraints</b>
1 <= n<= 1e5 (n is even)
1 <= arr[i] <= 1e5Return the minimum set size Sample Input :
10
3 3 3 3 5 5 5 2 2 7
Sample Output :
2
Explanation :
Choosing {3, 7} will make the new array [5, 5, 5, 2, 2] which has size 5 (i. e equal to half of the size of the old array).
Possible sets of size 2 are {3, 5}, {3, 2}, {5, 2}.
Choosing set {2, 7} is not possible as it will make the new array [3, 3, 3, 3, 5, 5, 5] which has a size greater than half of the size of the old array.
Sample Input 1:
5
7 7 7 7 7
Sample Output 1:
1
Explanation :
The only possible set you can choose is {7}. This will make the new array empty., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) throws IOException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
int arr[] = new int[n];
String[] str = br.readLine().trim().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(str[i]);
}
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
}
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
for (Map.Entry entry : map.entrySet()) {
maxHeap.add((Integer) entry.getValue());
}
long ans = 0;
int h=n/2;
int c=0;
while(ans<h) {
ans += maxHeap.poll();
c++;
}
System.out.println(c);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array, your task is to print the minimum size of the set so that at least half of the integers of the array are removed.The first line contains n the size of the array and the next line contains input of the array
<b>Constraints</b>
1 <= n<= 1e5 (n is even)
1 <= arr[i] <= 1e5Return the minimum set size Sample Input :
10
3 3 3 3 5 5 5 2 2 7
Sample Output :
2
Explanation :
Choosing {3, 7} will make the new array [5, 5, 5, 2, 2] which has size 5 (i. e equal to half of the size of the old array).
Possible sets of size 2 are {3, 5}, {3, 2}, {5, 2}.
Choosing set {2, 7} is not possible as it will make the new array [3, 3, 3, 3, 5, 5, 5] which has a size greater than half of the size of the old array.
Sample Input 1:
5
7 7 7 7 7
Sample Output 1:
1
Explanation :
The only possible set you can choose is {7}. This will make the new array empty., I have written this Solution Code: from collections import defaultdict
import numpy as np
n=int(input())
val=np.array([input().strip().split()],int).flatten()
d=defaultdict(int)
l=n
for i in val:
d[i]+=1
a=[]
for i in d:
a.append([d[i],i])
a.sort(reverse=True)
c=0
h=0
for i in a:
c+=1
h+=i[0]
if(h>(l//2-1)):
break
print(c), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array, your task is to print the minimum size of the set so that at least half of the integers of the array are removed.The first line contains n the size of the array and the next line contains input of the array
<b>Constraints</b>
1 <= n<= 1e5 (n is even)
1 <= arr[i] <= 1e5Return the minimum set size Sample Input :
10
3 3 3 3 5 5 5 2 2 7
Sample Output :
2
Explanation :
Choosing {3, 7} will make the new array [5, 5, 5, 2, 2] which has size 5 (i. e equal to half of the size of the old array).
Possible sets of size 2 are {3, 5}, {3, 2}, {5, 2}.
Choosing set {2, 7} is not possible as it will make the new array [3, 3, 3, 3, 5, 5, 5] which has a size greater than half of the size of the old array.
Sample Input 1:
5
7 7 7 7 7
Sample Output 1:
1
Explanation :
The only possible set you can choose is {7}. This will make the new array empty., I have written this Solution Code: /**
* Author : tourist1256
* Time : 2022-01-12 19:43:00
**/
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif
int minSetSize(vector<int> &arr) {
unordered_map<int, int> counter;
priority_queue<int> q;
int res = 0, removed = 0;
for (auto a : arr) counter[a]++;
for (auto c : counter) q.push(c.second);
while (removed < arr.size() / 2) {
removed += q.top();
q.pop();
res++;
}
return res;
}
int main() {
#ifdef LOCAL
auto start = std::chrono::high_resolution_clock::now();
#endif
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<int> a(n);
for (auto &it : a) {
cin >> it;
}
cout << minSetSize(a) << "\n";
#ifdef LOCAL
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start);
cerr << "Time taken : " << ((long double)duration.count()) / ((long double)1e9) << "s " << endl;
#endif
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a postfix expression, your task is to evaluate given expression.
Infix expression: The expression of the form a operator b. When an operator is in-between every pair of operands.
Postfix expression: The expression of the form a b operator. When an operator is followed for every pair of operands.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.The first line denotes the size of the string(which contains number or operand in form of string) i.e. N.
The next line contains string. The string contains an integer called operand or any of the four operators (+ - * /)
Constraints:-
1 <= n <= 40
1<=number<=500
Output the value of arithmetic expression formed using reverse Polish Notation.Input 1:
5
2 1 + 3 *
Output 1:
9
Explaination 1:
starting from backside:
*: ( )*( )
3: ()*(3)
+: ( () + () )*(3)
1: ( () + (1) )*(3)
2: ( (2) + (1) )*(3)
((2)+(1))*(3) = 9
Input 2:
5
4 13 5 / +
Output 2:
6
Explanation 2:
+: ()+()
/: ()+(() / ())
5: ()+(() / (5))
1: ()+((13) / (5))
4: (4)+((13) / (5))
(4)+((13) / (5)) = 6, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
String str[] = br.readLine().split(" ");
Stack <Integer> st = new Stack<>();
for(int i=0;i<t;i++){
char ch = str[i].charAt(0);
if(Character.isDigit(ch)){
st.push(Integer.parseInt(str[i]));
}
else{
int str1 = st.pop();
int str2 = st.pop();
switch(ch) {
case '+':
st.push(str2+str1);
break;
case '-':
st.push(str2- str1);
break;
case '/':
st.push(str2/str1);
break;
case '*':
st.push(str2*str1);
break;
}
}
}
System.out.println(st.peek());
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a postfix expression, your task is to evaluate given expression.
Infix expression: The expression of the form a operator b. When an operator is in-between every pair of operands.
Postfix expression: The expression of the form a b operator. When an operator is followed for every pair of operands.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.The first line denotes the size of the string(which contains number or operand in form of string) i.e. N.
The next line contains string. The string contains an integer called operand or any of the four operators (+ - * /)
Constraints:-
1 <= n <= 40
1<=number<=500
Output the value of arithmetic expression formed using reverse Polish Notation.Input 1:
5
2 1 + 3 *
Output 1:
9
Explaination 1:
starting from backside:
*: ( )*( )
3: ()*(3)
+: ( () + () )*(3)
1: ( () + (1) )*(3)
2: ( (2) + (1) )*(3)
((2)+(1))*(3) = 9
Input 2:
5
4 13 5 / +
Output 2:
6
Explanation 2:
+: ()+()
/: ()+(() / ())
5: ()+(() / (5))
1: ()+((13) / (5))
4: (4)+((13) / (5))
(4)+((13) / (5)) = 6, I have written this Solution Code: stack = []
n = int(input())
exp = [i for i in input().split()]
for i in exp:
try:
stack.append(int(i))
except:
a1 = stack.pop()
a2 = stack.pop()
if i == '+':
stack.append(a1+a2)
if i == '-':
stack.append(a2-a1)
if i == '/':
stack.append(a2//a1)
if i == '*':
stack.append(a1*a2)
print(*stack), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a postfix expression, your task is to evaluate given expression.
Infix expression: The expression of the form a operator b. When an operator is in-between every pair of operands.
Postfix expression: The expression of the form a b operator. When an operator is followed for every pair of operands.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.The first line denotes the size of the string(which contains number or operand in form of string) i.e. N.
The next line contains string. The string contains an integer called operand or any of the four operators (+ - * /)
Constraints:-
1 <= n <= 40
1<=number<=500
Output the value of arithmetic expression formed using reverse Polish Notation.Input 1:
5
2 1 + 3 *
Output 1:
9
Explaination 1:
starting from backside:
*: ( )*( )
3: ()*(3)
+: ( () + () )*(3)
1: ( () + (1) )*(3)
2: ( (2) + (1) )*(3)
((2)+(1))*(3) = 9
Input 2:
5
4 13 5 / +
Output 2:
6
Explanation 2:
+: ()+()
/: ()+(() / ())
5: ()+(() / (5))
1: ()+((13) / (5))
4: (4)+((13) / (5))
(4)+((13) / (5)) = 6, I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
class Solution {
public:
int evalRPN(vector<string> &tokens) {
int size = tokens.size();
if (size == 0)
return 0;
std::stack<int> operands;
for (int i = 0; i < size; ++i)
{
std::string cur_token = tokens[i];
if ((cur_token == "*") || (cur_token == "/") || (cur_token == "+") || (cur_token == "-"))
{
int opr2 = operands.top();
operands.pop();
int opr1 = operands.top();
operands.pop();
int result = this->eval(opr1, opr2, cur_token);
operands.push(result);
}
else{
operands.push(std::atoi(cur_token.c_str()));
}
}
return operands.top();
}
int eval(int opr1, int opr2, string opt)
{
if (opt == "*")
{
return opr1 * opr2;
}
else if (opt == "+")
{
return opr1 + opr2;
}
else if (opt == "-")
{
return opr1 - opr2;
}
else if (opt == "/")
{
return opr1 / opr2;
}
return 0;
}
};
signed main() {
IOS;
int n; cin >> n;
vector<string> v(n, "");
for(int i = 0; i < n; i++)
cin >> v[i];
Solution s;
cout << s.evalRPN(v);
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You have N cakes and there are K people. You want to distribute cake among these K people such that following conditions are satisfied:
> You cannot give N cakes to a single person.
> All the people who get atleast one cake should all get same number of cakes.
> You must distribute all N cakes.
Find out if it is possible to distribute the cakes.Input contains two integers N and K.
Constraints:
1 <= N <= 10^18
1 <= K <= 10^6If it is possible to distribute cakes print "Yes" else print "No".Sample Input 1
10 3
Sample Output 1
Yes
Explanation: We can give 5 cakes to person 1 and 5 to person 2 and no cake to person 3.
Sample Input 2
5 4
Sample Output 2
No, I have written this Solution Code: import java.io.*;
import java.util.*;
import java.io.IOException;
class Main {
static boolean call(long n1, long n2){
if((n1%3== 0 && n2>3) || (n1%5== 0 && n2>5) || (n1%7== 0 && n2>7) || (n1%9== 0 && n2>9))
return true;
for(int i=11;i<n2;i+=2){
if(n1%i== 0){
return true;
}
}
return false;
}
public static void main (String[] args) throws IOException {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String[] input= br.readLine().split(" ");
Long n1= Long.parseLong(input[0]);
Long n2= Long.parseLong(input[1]);
if(n2<2){
System.out.print("No");
}
else if(n1%n2== 0 || n1%2==0 || n1<n2){
System.out.print("Yes");
}
else if(call(n1,n2)){
System.out.print("Yes");
}
else{
System.out.print("No");
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You have N cakes and there are K people. You want to distribute cake among these K people such that following conditions are satisfied:
> You cannot give N cakes to a single person.
> All the people who get atleast one cake should all get same number of cakes.
> You must distribute all N cakes.
Find out if it is possible to distribute the cakes.Input contains two integers N and K.
Constraints:
1 <= N <= 10^18
1 <= K <= 10^6If it is possible to distribute cakes print "Yes" else print "No".Sample Input 1
10 3
Sample Output 1
Yes
Explanation: We can give 5 cakes to person 1 and 5 to person 2 and no cake to person 3.
Sample Input 2
5 4
Sample Output 2
No, I have written this Solution Code: l=list(map(int,input().split()))
flag=0
for i in range(2,l[1]+1):
if(l[0]%i==0):
flag=1
print("Yes")
break
if(flag==0):
print("No"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You have N cakes and there are K people. You want to distribute cake among these K people such that following conditions are satisfied:
> You cannot give N cakes to a single person.
> All the people who get atleast one cake should all get same number of cakes.
> You must distribute all N cakes.
Find out if it is possible to distribute the cakes.Input contains two integers N and K.
Constraints:
1 <= N <= 10^18
1 <= K <= 10^6If it is possible to distribute cakes print "Yes" else print "No".Sample Input 1
10 3
Sample Output 1
Yes
Explanation: We can give 5 cakes to person 1 and 5 to person 2 and no cake to person 3.
Sample Input 2
5 4
Sample Output 2
No, I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int n,k;
cin>>n>>k;
for(int i=2;i<=k;++i){
if(n%i==0){
cout<<"Yes";
return 0;
}
}
cout<<"No";
#ifdef ANIKET_GOYAL
// cout<<endl<<endl<<endl<<endl<<"Time elapsed: "<<(double)(clock()-clk)/CLOCKS_PER_SEC<<endl;
#endif
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a binary tree containing with N nodes and an integer X. Your task is to complete the function countSubtreesWithSumX() that returns the count of the number of subtress having total node’s data sum equal to a value X.
Example: A tree given below<b>User Task:</b>
Since this will be a functional problem. You don't have to take input. You just have to complete the function <b>countSubtreesWithSumX()</b> that takes "root" node and the integer x as parameter.
<b>Constraints:</b>
1 <= T <= 100
1 <= N <= 10^3
1 <= node values <= 10^4
<b>Sum of "N" over all testcases does not exceed 10^5</b>Return the number of subtrees with sum X. The driver code will take care of printing it.Sample Input:
1
3 5
1 2 3
Sum=5
Tree:-
1
/ \
2 3
Sample Output:
0
Explanation:
No subtree has a sum equal to 5.
Sample Input:-
1
5 5
2 1 3 4 5
Sum=5
Tree:-
2
/ \
1 3
/ \
4 5
Sample Output:-
1, I have written this Solution Code: static int c = 0;
static int countSubtreesWithSumXUtil(Node root,int x)
{
// if tree is empty
if (root==null)return 0;
// sum of nodes in the left subtree
int ls = countSubtreesWithSumXUtil(root.left,x);
// sum of nodes in the right subtree
int rs = countSubtreesWithSumXUtil(root.right, x);
int sum = ls + rs + root.data;
// if tree's nodes sum == x
if (sum == x)c++;
return sum;
}
static int countSubtreesWithSumX(Node root, int x)
{
c = 0;
// if tree is empty
if (root==null)return 0;
// sum of nodes in the left subtree
int ls = countSubtreesWithSumXUtil(root.left, x);
// sum of nodes in the right subtree
int rs = countSubtreesWithSumXUtil(root.right, x);
// check if above sum is equal to x
if ((ls + rs + root.data) == x)c++;
return c;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string s, find the first non-repeating character in the string and return its index. If it does not exist, return -1.First line of the input contains the string s.
<b>Constraints</b>
1<= s. length <= 100000Print the index of the first non- repeating character in a stringInput
s = "newtonschool"
Output
1
Explanation
"e" is the first non- repeating character in a string, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
System.out.print(nonRepeatChar(s));
}
static int nonRepeatChar(String s){
char count[] = new char[256];
for(int i=0; i< s.length(); i++){
count[s.charAt(i)]++;
}
for (int i=0; i<s.length(); i++) {
if (count[s.charAt(i)]==1){
return i;
}
}
return -1;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string s, find the first non-repeating character in the string and return its index. If it does not exist, return -1.First line of the input contains the string s.
<b>Constraints</b>
1<= s. length <= 100000Print the index of the first non- repeating character in a stringInput
s = "newtonschool"
Output
1
Explanation
"e" is the first non- repeating character in a string, I have written this Solution Code: from collections import defaultdict
s=input()
d=defaultdict(int)
for i in s:
d[i]+=1
ans=-1
for i in range(len(s)):
if(d[s[i]]==1):
ans=i
break
print(ans), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string s, find the first non-repeating character in the string and return its index. If it does not exist, return -1.First line of the input contains the string s.
<b>Constraints</b>
1<= s. length <= 100000Print the index of the first non- repeating character in a stringInput
s = "newtonschool"
Output
1
Explanation
"e" is the first non- repeating character in a string, I have written this Solution Code: /**
* Author : tourist1256
* Time : 2022-01-10 12:51:16
**/
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 2351
#endif
int firstUniqChar(string s) {
map<char, int> charCount;
int len = s.length();
for (int i = 0; i < len; i++) {
charCount[s[i]]++;
}
for (int i = 0; i < len; i++) {
if (charCount[s[i]] == 1)
return i;
}
return -1;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
string str;
cin>>str;
cout<<firstUniqChar(str)<<"\n";
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, your task is to print the sum of its digits.<b>User Task</b>
Since this is a functional problem, you don't have to worry about the input. You just have to complete the function <i>SumOfDigits()</i> which contains the given number N.
<b>Constraints:</b>
1 <= N <= 10<sup>5</sup>
<b>Note:</b>
<i>But there is a catch here given user function has already code in it which may or may not be correct, now you need to figure out these and correct if it is required</i>Return the sum of its digits.Sample Input:-
12
Sample Output:-
3
Sample Input:-
99
Sample Output:-
18, I have written this Solution Code: x=int(input())
y=str(x)
t=0
for i in range(len(y)):
t=t+int(y[i])
print(t), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, your task is to print the sum of its digits.<b>User Task</b>
Since this is a functional problem, you don't have to worry about the input. You just have to complete the function <i>SumOfDigits()</i> which contains the given number N.
<b>Constraints:</b>
1 <= N <= 10<sup>5</sup>
<b>Note:</b>
<i>But there is a catch here given user function has already code in it which may or may not be correct, now you need to figure out these and correct if it is required</i>Return the sum of its digits.Sample Input:-
12
Sample Output:-
3
Sample Input:-
99
Sample Output:-
18, I have written this Solution Code: static int SumOfDigits(int N)
{
int sum = 0;
while(N >0)
{
sum+= N%10;
N = N/10;
}
return sum;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a string S consisting of lowercase English letters. Determine whether adding some number of a's (possibly zero) at the beginning of S can make it a palindrome.The input consists of a single string S.
Constraints
1 ≤ ∣S∣ ≤ 10^6
S consists of lowercase English letters.If adding some number of a's (possibly zero) at the beginning of S can make it a palindrome, print Yes; otherwise, print No.<b>Sample Input 1</b>
kasaka
<b>Sample Output 1</b>
Yes
<b>Sample Input 2</b>
reveh
<b>Sample Output 2</b>
No, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(void) {
int n, x, y;
string a;
cin >> a;
n = a.size();
x = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 'a')x++;
else break;
}
y = 0;
for (int i = n - 1; i >= 0; i--) {
if (a[i] == 'a')y++;
else break;
}
if (x == n) {
cout << "Yes" << endl;
return 0;
}
if (x > y) {
cout << "No" << endl;
return 0;
}
for (int i = x; i < (n - y); i++) {
if (a[i] != a[x + n - y - i - 1]) {
cout << "No" << endl;
return 0;
}
}
cout << "Yes" << endl;
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A and an integer K. Find the maximum for each and every contiguous subarray of size K.
Problem asked in Amazon, Flipkart.The first line of each test case contains a single integer N denoting the size of array and the size of subarray K. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Constraints:
1 ≤ N ≤ 10^5
1 ≤ K ≤ N
0 ≤ A[i] <= 10^5Print the maximum for every subarray of size K.Sample Input:
9 3
1 2 3 1 4 5 2 3 6
Sample Output:
3 3 4 5 5 5 6
Explanation:
Starting from the first subarray of size k = 3, we have 3 as maximum. Moving the window forward, maximum element are as 3, 4, 5, 5, 5 and 6., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void printMax(int arr[], int n, int k) {
int j, max;
for(int i = 0; i <= n - k; i++) {
max = arr[i];
for(j = 1; j < k; j++) {
if(arr[i + j] > max) {
max = arr[i + j];
}
}
System.out.print(max + " ");
}
}
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str1[] = br.readLine().trim().split(" ");
int n = Integer.parseInt(str1[0]);
int k = Integer.parseInt(str1[1]);
String str2[] = br.readLine().trim().split(" ");
int arr[] = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(str2[i]);
}
printMax(arr, n ,k);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A and an integer K. Find the maximum for each and every contiguous subarray of size K.
Problem asked in Amazon, Flipkart.The first line of each test case contains a single integer N denoting the size of array and the size of subarray K. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Constraints:
1 ≤ N ≤ 10^5
1 ≤ K ≤ N
0 ≤ A[i] <= 10^5Print the maximum for every subarray of size K.Sample Input:
9 3
1 2 3 1 4 5 2 3 6
Sample Output:
3 3 4 5 5 5 6
Explanation:
Starting from the first subarray of size k = 3, we have 3 as maximum. Moving the window forward, maximum element are as 3, 4, 5, 5, 5 and 6., I have written this Solution Code: n,k=input().split()
n=int(n)
k=int(k)
arr=input().split()
for i in range(0,n):
arr[i]=int(arr[i])
m=max(arr[0:k])
for i in range(k-1,n):
if(arr[i] > m):
m=arr[i]
if(arr[i-k]==m):
m=max(arr[i-k+1:i+1])
print (m, end=' '), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A and an integer K. Find the maximum for each and every contiguous subarray of size K.
Problem asked in Amazon, Flipkart.The first line of each test case contains a single integer N denoting the size of array and the size of subarray K. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Constraints:
1 ≤ N ≤ 10^5
1 ≤ K ≤ N
0 ≤ A[i] <= 10^5Print the maximum for every subarray of size K.Sample Input:
9 3
1 2 3 1 4 5 2 3 6
Sample Output:
3 3 4 5 5 5 6
Explanation:
Starting from the first subarray of size k = 3, we have 3 as maximum. Moving the window forward, maximum element are as 3, 4, 5, 5, 5 and 6., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
// A Dequeue (Double ended queue) based method for printing maximum element of
// all subarrays of size k
void printKMax(int arr[], int n, int k)
{
// Create a Double Ended Queue, Qi that will store indexes of array elements
// The queue will store indexes of useful elements in every window and it will
// maintain decreasing order of values from front to rear in Qi, i.e.,
// arr[Qi.front[]] to arr[Qi.rear()] are sorted in decreasing order
std::deque<int> Qi(k);
/* Process first k (or first window) elements of array */
int i;
for (i = 0; i < k; ++i) {
// For every element, the previous smaller elements are useless so
// remove them from Qi
while ((!Qi.empty()) && arr[i] >= arr[Qi.back()])
Qi.pop_back(); // Remove from rear
// Add new element at rear of queue
Qi.push_back(i);
}
// Process rest of the elements, i.e., from arr[k] to arr[n-1]
for (; i < n; ++i) {
// The element at the front of the queue is the largest element of
// previous window, so print it
cout << arr[Qi.front()] << " ";
// Remove the elements which are out of this window
while ((!Qi.empty()) && Qi.front() <= i - k)
Qi.pop_front(); // Remove from front of queue
// Remove all elements smaller than the currently
// being added element (remove useless elements)
while ((!Qi.empty()) && arr[i] >= arr[Qi.back()])
Qi.pop_back();
// Add current element at the rear of Qi
Qi.push_back(i);
}
// Print the maximum element of last window
cout << arr[Qi.front()];
}
// Driver program to test above functions
int main()
{
int n,k;
cin>>n>>k;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
printKMax(arr, n, k);
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a function <code>reverseString</code>, which takes in a string as a parameter. Your task is to complete the function such that it returns the reverse of the string.(hello changes to olleh)
// Complete the reverseString function
function reverseString(n) {
//Write Code Here
}A string nReturns the reverse of nconst n = 'hello'
reverseString(n) //displays 'olleh' in console, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String n=sc.nextLine();
char tra[] = n.toCharArray();
for(int i=tra.length-1;i>=0;i--){
System.out.print(tra[i]);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a function <code>reverseString</code>, which takes in a string as a parameter. Your task is to complete the function such that it returns the reverse of the string.(hello changes to olleh)
// Complete the reverseString function
function reverseString(n) {
//Write Code Here
}A string nReturns the reverse of nconst n = 'hello'
reverseString(n) //displays 'olleh' in console, I have written this Solution Code: function reverseString (n) {
return n.split("").reverse().join("");
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: After saving the planet of Xander in 2014 from Ronan, the guardians of the galaxy decided to play a game on it. Between the vast furious oceans, they discover a row of buildings. The buildings are of different heights arranged at each index along a number line. Gamora starts at building 0 and a height of 0. Groot gets the task to <b>determine the minimum thrust that Gamora needs at the start of the game so that she can jump to the top of each building without her thrust going below zero</b>. Write a code to help Groot with his task.
The units of height relate directly to units of thrust. Gamora’s thrust level is calculated as follows:
• If gamora's thrust is less than the height of the building, her new thrust = gamora's thrust – (height – gamora's thrust)
• If gamora's thrust is greater than equal to the height of the building, her new thrust = gamora's thrust + (gamora's thrust - height)The first line contains an integer n, the number of buildings.
The second line n space-separated integers, arr[1], arr[2]…arr[n], the heights of the building.
<b>Constraints:-</b>
1 ≤ n ≤ 10<sup>5</sup>
1 ≤ arr[i] ≤ 10<sup>5</sup>The output contains a single integer denoting the minimum thrust Gamora needs at the start of the game.Sample Input:-
5
3 4 3 2 4
Sample Output:-
4
Explanation:-
If we take 3 then:-
at index 1:- 3 + 3-3 = 3
at index 2:- 3 - (4-3) = 2
at index 3:- 2 - (3-2) = 1
at index 4:- 1 - (2-1) = 0
Sample Input:-
3
4 4 4
Sample Output:-
4, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
FastReader sc = new FastReader();
int n = sc.nextInt();
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i]= sc.nextLong();
}
long l = 0;
long r= 1000000000;
long x=0;
while (l!=r){
x= (l+r)/2;
if(checkThrust(arr,x)) {
r=x;
}
else {
l=x+1;
}
}
System.out.print(l);
}
static boolean checkThrust(long[] arr,long r){
long thrust = r;
for (int i = 0; i < arr.length; i++) {
thrust = 2*thrust-arr[i];
if(thrust>=1000000000000L) return true;
if(thrust<0) return false;
}
return true;
}
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 {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: After saving the planet of Xander in 2014 from Ronan, the guardians of the galaxy decided to play a game on it. Between the vast furious oceans, they discover a row of buildings. The buildings are of different heights arranged at each index along a number line. Gamora starts at building 0 and a height of 0. Groot gets the task to <b>determine the minimum thrust that Gamora needs at the start of the game so that she can jump to the top of each building without her thrust going below zero</b>. Write a code to help Groot with his task.
The units of height relate directly to units of thrust. Gamora’s thrust level is calculated as follows:
• If gamora's thrust is less than the height of the building, her new thrust = gamora's thrust – (height – gamora's thrust)
• If gamora's thrust is greater than equal to the height of the building, her new thrust = gamora's thrust + (gamora's thrust - height)The first line contains an integer n, the number of buildings.
The second line n space-separated integers, arr[1], arr[2]…arr[n], the heights of the building.
<b>Constraints:-</b>
1 ≤ n ≤ 10<sup>5</sup>
1 ≤ arr[i] ≤ 10<sup>5</sup>The output contains a single integer denoting the minimum thrust Gamora needs at the start of the game.Sample Input:-
5
3 4 3 2 4
Sample Output:-
4
Explanation:-
If we take 3 then:-
at index 1:- 3 + 3-3 = 3
at index 2:- 3 - (4-3) = 2
at index 3:- 2 - (3-2) = 1
at index 4:- 1 - (2-1) = 0
Sample Input:-
3
4 4 4
Sample Output:-
4, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
const long long linf = 0x3f3f3f3f3f3f3f3fLL;
const int N = 111111;
int n;
int h[N];
int check(long long x) {
long long energy = x;
for(int i = 1; i <= n; i++) {
energy += energy - h[i];
if(energy >= linf) return 1;
if(energy < 0) return 0;
}
return 1;
}
int main() {
cin >> n;
for(int i = 1; i <= n; i++) {
cin >> h[i];
}
long long L = 0, R = linf;
long long ans=0;
while(L < R) {
long long M = (L + R) / 2;
if(check(M)) {
R = M;
ans=M;
} else {
L = M + 1;
}
}
cout << ans << endl;
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N people are waiting in line to get food. The ith person takes Arr[i] amount of time to get food. A person is happy if the amount of time he has to wait is less than or equal to the amount of time he takes to get food. The time a person waits is the sum of time people in front of him take to get food. Now you have to rearrange the people in the line such that the maximum number of people in the line are happy and report the maximum number of people that can be happy.The first line of input contains a single integer N.
The second line of input contains N integers denoting Arr[i].
Constraints:
1 <= N <= 100000
1 <= Arr[i] <= 1000000000Print the maximum number of people that can be happy after the rearrangement.Sample Input
4
3 1 3 10
Sample Output
3
Explanation:
The optimal arrangement is 1 3 10 3
This way person 1 waits 0 units so he is happy.
Person 2 waits for 1 unit so he is happy.
Person 3 waits for 4 units so is happy.
Person 4 waits 14 units so he is unhappy., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(in.readLine());
String s[]=in.readLine().split(" ");
long[] a=new long[n];
for(int i=0;i<n;i++){
a[i]=Long.parseLong(s[i]);
}
long sum=0;
int count=0;
Arrays.sort(a);
for(int i=0;i<n;i++){
if(sum<=a[i]){
sum+=a[i];
count++;
}
}
System.out.print(count);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N people are waiting in line to get food. The ith person takes Arr[i] amount of time to get food. A person is happy if the amount of time he has to wait is less than or equal to the amount of time he takes to get food. The time a person waits is the sum of time people in front of him take to get food. Now you have to rearrange the people in the line such that the maximum number of people in the line are happy and report the maximum number of people that can be happy.The first line of input contains a single integer N.
The second line of input contains N integers denoting Arr[i].
Constraints:
1 <= N <= 100000
1 <= Arr[i] <= 1000000000Print the maximum number of people that can be happy after the rearrangement.Sample Input
4
3 1 3 10
Sample Output
3
Explanation:
The optimal arrangement is 1 3 10 3
This way person 1 waits 0 units so he is happy.
Person 2 waits for 1 unit so he is happy.
Person 3 waits for 4 units so is happy.
Person 4 waits 14 units so he is unhappy., I have written this Solution Code: n = int(input())
li = input().split()
li = list(map(int, li))
curr = 0
ans = 0
li.sort()
for i in li:
if i >= curr:
curr += i
ans += 1
print(ans), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N people are waiting in line to get food. The ith person takes Arr[i] amount of time to get food. A person is happy if the amount of time he has to wait is less than or equal to the amount of time he takes to get food. The time a person waits is the sum of time people in front of him take to get food. Now you have to rearrange the people in the line such that the maximum number of people in the line are happy and report the maximum number of people that can be happy.The first line of input contains a single integer N.
The second line of input contains N integers denoting Arr[i].
Constraints:
1 <= N <= 100000
1 <= Arr[i] <= 1000000000Print the maximum number of people that can be happy after the rearrangement.Sample Input
4
3 1 3 10
Sample Output
3
Explanation:
The optimal arrangement is 1 3 10 3
This way person 1 waits 0 units so he is happy.
Person 2 waits for 1 unit so he is happy.
Person 3 waits for 4 units so is happy.
Person 4 waits 14 units so he is unhappy., I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
typedef unsigned long long ull;
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
signed main(){
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int n;
cin >> n;
int arr[n];
for(int i = 0; i < n;i++) cin >> arr[i];
sort(arr,arr+n);
int cur=0;
int ans = 0;
for(int i = 0; i < n;i++){
if(cur <= arr[i]) cur += arr[i],ans++;
}
cout << ans << endl;
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, find the closest prime number to N. If there are multiple print the smaller one.The input contains a single integer N.
Constraints:
1 <= N <= 1000000000Print the closest prime to N.Sample Input 1
12
Sample Output 1
11
Explanation: Closest prime to 12 is 11 and 13 smaller of which is 11.
Sample Input 2
17
Sample Output 2
17
Explanation: Closest prime to 17 is 17., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
if(n==1){
System.out.println(2);
}else{
int after = afterPrime(n);
int before = beforePrime(n);
if(before>after){
System.out.println(n+after);
}
else{System.out.println(n-before);}
}
}
public static boolean isPrime(int n)
{
int count=0;
for(int i=2;i*i<n;i++)
{
if(n%i==0)
count++;
}
if(count==0)
return true;
else
return false;
}
public static int beforePrime(int n)
{
int c=0;
while(true)
{
if(isPrime(n))
return c;
else
{
n=n-1;
c++;
}
}
}
public static int afterPrime(int n)
{
int c=0;
while(true)
{
if(isPrime(n))
return c;
else
{
n=n+1;
c++;
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, find the closest prime number to N. If there are multiple print the smaller one.The input contains a single integer N.
Constraints:
1 <= N <= 1000000000Print the closest prime to N.Sample Input 1
12
Sample Output 1
11
Explanation: Closest prime to 12 is 11 and 13 smaller of which is 11.
Sample Input 2
17
Sample Output 2
17
Explanation: Closest prime to 17 is 17., I have written this Solution Code: from math import sqrt
def NearPrime(N):
if N >1:
for i in range(2,int(sqrt(N))+1):
if N%i ==0:
return False
break
else: return True
else: return False
N=int(input())
i =0
while NearPrime(N-i)==False and NearPrime(N+i)==False:
i+=1
if NearPrime(N-i) and NearPrime(N+i):print(N-i)
elif NearPrime(N-i):print(N-i)
elif NearPrime(N+i): print(N+i), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, find the closest prime number to N. If there are multiple print the smaller one.The input contains a single integer N.
Constraints:
1 <= N <= 1000000000Print the closest prime to N.Sample Input 1
12
Sample Output 1
11
Explanation: Closest prime to 12 is 11 and 13 smaller of which is 11.
Sample Input 2
17
Sample Output 2
17
Explanation: Closest prime to 17 is 17., I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
bool isPrime(int n){
if(n<=1)
return false;
for(int i=2;i*i<=n;++i)
if(n%i==0)
return false;
return true;
}
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int n;
cin>>n;
if(n==1)
cout<<"2";
else{
int v1=n,v2=n;
while(isPrime(v1)==false)
--v1;
while(isPrime(v2)==false)
++v2;
if(v2-n==n-v1)
cout<<v1;
else{
if(v2-n<n-v1)
cout<<v2;
else
cout<<v1;
}
}
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, your task is to return the sum of all of its divisors.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>SumOfDivisors()</b> that takes the integer N as parameter.
Constraints:-
1<=N<=10^9Return the sum of all of the divisors.Sample Input:-
4
Sample Output:-
7
Sample Input:-
13
Sample Output:-
14, I have written this Solution Code: public static long SumOfDivisors(long N){
long sum=0;
long c=(long)Math.sqrt(N);
for(long i=1;i<=c;i++){
if(N%i==0){
sum+=i;
if(i*i!=N){sum+=N/i;}
}
}
return sum;
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, your task is to return the sum of all of its divisors.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>SumOfDivisors()</b> that takes the integer N as parameter.
Constraints:-
1<=N<=10^9Return the sum of all of the divisors.Sample Input:-
4
Sample Output:-
7
Sample Input:-
13
Sample Output:-
14, I have written this Solution Code:
long long SumOfDivisors(long long N){
long long sum=0;
long sq=sqrt(N);
for(long i=1;i<=sq;i++){
if(N%i==0){
sum+=i;
if(i*i!=N){
sum+=N/i;
}
}
}
return sum;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, your task is to return the sum of all of its divisors.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>SumOfDivisors()</b> that takes the integer N as parameter.
Constraints:-
1<=N<=10^9Return the sum of all of the divisors.Sample Input:-
4
Sample Output:-
7
Sample Input:-
13
Sample Output:-
14, I have written this Solution Code:
long long SumOfDivisors(long long N){
long long sum=0;
long sq=sqrt(N);
for(long i=1;i<=sq;i++){
if(N%i==0){
sum+=i;
if(i*i!=N){
sum+=N/i;
}
}
}
return sum;
}, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, your task is to return the sum of all of its divisors.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>SumOfDivisors()</b> that takes the integer N as parameter.
Constraints:-
1<=N<=10^9Return the sum of all of the divisors.Sample Input:-
4
Sample Output:-
7
Sample Input:-
13
Sample Output:-
14, I have written this Solution Code:
def SumOfDivisors(num) :
# Final result of summation of divisors
result = 0
# find all divisors which divides 'num'
i = 1
while i<= (math.sqrt(num)) :
# if 'i' is divisor of 'num'
if (num % i == 0) :
# if both divisors are same then
# add it only once else add both
if (i == (num / i)) :
result = result + i;
else :
result = result + (i + num/i);
i = i + 1
# Add 1 to the result as 1 is also
# a divisor
return (result); , In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given 3 non-negative integers A, B and C. In one operation, you can pick any two of the given integers and subtract one from both of them.
If it is possible to make all the 3 integers zero after some number of operations (possibly none), print "Yes". Otherwise, print "No".The first line contains a single integer T – the number of test cases.
Each of the next T lines contains 3 space separated integers A, B and C respectively.
<b> Constraints: </b>
1 ≤ T ≤ 10
0 ≤ A, B, C ≤ 10Output T lines, the i<sup>th</sup> line containing a single word, either "Yes" or "No" – the answer to the i<sup>th</sup> test case.Sample Input 1:
2
3 4 2
2 2 2
Sample Output 1:
No
Yes
Sample Explanation 1:
For the first test case, there is no possible way to make all the elements zero.
For the second test case, we can pick elements in the following order: (A,B), (B,C), (A,C), I have written this Solution Code: import java.util.*;
import java.lang.*;
import java.io.*;
class Main {
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st==null || !st.hasMoreTokens()){
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().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
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("").append(String.valueOf(object));
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
public static void main(String[] args) throws Exception{
try {
FastReader in=new FastReader();
FastWriter out = new FastWriter();
int testCases=in.nextInt();
while(testCases-- > 0) {
int a = in.nextInt(), b = in.nextInt(), c = in.nextInt();
while ((a>0&&b>0)||(a>0&&c>0)||(b>0&&c>0)) {
if (a >= b && a >= c) {
a--;
if (b >= c) {
b--;
}
else{
c--;
}
}
else if (b >= a && b >= c) {
b--;
if (a >= c) {
a--;
}
else{
c--;
}
}
else{
c--;
if (a >= b) {
a--;
}
else{
b--;
}
}
}
if (a==0&&b==0&&c==0){
out.println("Yes");
}
else{
out.println("No");
}
}
out.close();
} catch (Exception e) {
return;
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given 3 non-negative integers A, B and C. In one operation, you can pick any two of the given integers and subtract one from both of them.
If it is possible to make all the 3 integers zero after some number of operations (possibly none), print "Yes". Otherwise, print "No".The first line contains a single integer T – the number of test cases.
Each of the next T lines contains 3 space separated integers A, B and C respectively.
<b> Constraints: </b>
1 ≤ T ≤ 10
0 ≤ A, B, C ≤ 10Output T lines, the i<sup>th</sup> line containing a single word, either "Yes" or "No" – the answer to the i<sup>th</sup> test case.Sample Input 1:
2
3 4 2
2 2 2
Sample Output 1:
No
Yes
Sample Explanation 1:
For the first test case, there is no possible way to make all the elements zero.
For the second test case, we can pick elements in the following order: (A,B), (B,C), (A,C), I have written this Solution Code: t=int(input())
for i in range(t):
arr=list(map(int,input().split()))
a,b,c=sorted(arr)
if((a+b+c)%2):
print("No")
elif ((a+b)>=c):
print("Yes")
else:
print("No"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given 3 non-negative integers A, B and C. In one operation, you can pick any two of the given integers and subtract one from both of them.
If it is possible to make all the 3 integers zero after some number of operations (possibly none), print "Yes". Otherwise, print "No".The first line contains a single integer T – the number of test cases.
Each of the next T lines contains 3 space separated integers A, B and C respectively.
<b> Constraints: </b>
1 ≤ T ≤ 10
0 ≤ A, B, C ≤ 10Output T lines, the i<sup>th</sup> line containing a single word, either "Yes" or "No" – the answer to the i<sup>th</sup> test case.Sample Input 1:
2
3 4 2
2 2 2
Sample Output 1:
No
Yes
Sample Explanation 1:
For the first test case, there is no possible way to make all the elements zero.
For the second test case, we can pick elements in the following order: (A,B), (B,C), (A,C), I have written this Solution Code:
// #pragma GCC optimize("Ofast")
// #pragma GCC target("avx,avx2,fma")
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#define pi 3.141592653589793238
#define int long long
#define ll long long
#define ld long double
using namespace __gnu_pbds;
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
long long powm(long long a, long long b,long long mod) {
long long res = 1;
while (b > 0) {
if (b & 1)
res = res * a %mod;
a = a * a %mod;
b >>= 1;
}
return res;
}
ll gcd(ll a, ll b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(0);
#ifndef ONLINE_JUDGE
if(fopen("input.txt","r"))
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
}
#endif
int t;
cin>>t;
while(t--)
{
int a,b,c;
cin>>a>>b>>c;
if(a>b+c||b>a+c||c>a+b)
cout<<"No\n";
else
{
int sum=a+b+c;
if(sum%2)
cout<<"No\n";
else
cout<<"Yes\n";
}
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Write a function called lucky_sevens which takes an array of integers and returns true if any three consecutive elements sum to 7An array containing numbers.Print true if such triplet exists summing to 7 else print falseSample input:-
[2, 1, 5, 1, 0]
[1, 6]
Sample output:-
true
false
Explanation:-
1+5+1 = 7
no 3 consecutive numbers so false, I have written this Solution Code: function lucky_sevens(arr) {
// if less than 3 elements then this challenge is not possible
if (arr.length < 3) {
console.log(false)
return;
}
// because we know there are at least 3 elements we can
// start the loop at the 3rd element in the array (i=2)
// and check it along with the two previous elements (i-1) and (i-2)
for (let i = 2; i < arr.length; i++) {
if (arr[i] + arr[i-1] + arr[i-2] === 7) {
console.log(true)
return;
}
}
// if loop is finished and no elements summed to 7
console.log(false)
}
, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: static int isPresent(long arr[], int n, long k)
{
int left = 0;
int right = n-1;
int res = -1;
while(left<=right){
int mid = (left+right)/2;
if(arr[mid] == k){
res = 1;
break;
}else if(arr[mid] < k){
left = mid + 1;
}else{
right = mid - 1;
}
}
return res;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
unordered_map<long long,int> m;
long k;
cin>>k;
long long a;
for(int i=0;i<n;i++){
cin>>a;
m[a]++;
}
if(m.find(k)!=m.end()){
cout<<1<<endl;
}
else{
cout<<-1<<endl;
}
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return 1
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
def position(n,arr,x):
return binary_search(arr,0,n-1,x)
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: // arr is they array to search from
// x is target
function binSearch(arr, x) {
// write code here
// do not console.log
// return the 1 or -1
let l = 0;
let r = arr.length - 1;
let mid;
while (r >= l) {
mid = l + Math.floor((r - l) / 2);
// If the element is present at the middle
// itself
if (arr[mid] == x)
return 1;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
r = mid - 1;
// Else the element can only be present
// in right subarray
else
l = mid + 1;
}
// We reach here when element is not
// present in array
return -1;
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two strings a and b consisting of lowercase characters. The task is to check whether two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, “act” and “tac” are an anagram of each other.Input consists of two strings in lowercase english characters.
Constraints:
1 ≤ |s1|, |s2| ≤ 10^5Print "YES" without quotes if the two strings are anagram else print "NO".Sample Input
naman
manan
Sample Output
YES
Explanation: Both String contain 2 'a's, 2 'n's and 1 'm'., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s1 = br.readLine();
String s2 = br.readLine();
boolean flag = true;
int[] arr1 = new int[26];
int[] arr2 = new int[26];
for(int i=0; i<s1.length(); i++){
arr1[s1.charAt(i)-97]++;
}
for(int i=0; i<s2.length(); i++){
arr2[s2.charAt(i)-97]++;
}
for(int i=0; i<25; i++){
if(arr1[i]!=arr2[i]){
flag = false;
break;
}
}
if(flag==true)
System.out.print("YES");
else System.out.print("NO");
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two strings a and b consisting of lowercase characters. The task is to check whether two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, “act” and “tac” are an anagram of each other.Input consists of two strings in lowercase english characters.
Constraints:
1 ≤ |s1|, |s2| ≤ 10^5Print "YES" without quotes if the two strings are anagram else print "NO".Sample Input
naman
manan
Sample Output
YES
Explanation: Both String contain 2 'a's, 2 'n's and 1 'm'., I have written this Solution Code: s1 = input().strip()
s2 = input().strip()
dict1 = dict()
dict2 = dict()
for i in s1:
dict1[i] = dict1.get(i, 0) + 1
for j in s2:
dict2[j] = dict2.get(j, 0) + 1
print(("NO", "YES")[dict1 == dict2]), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two strings a and b consisting of lowercase characters. The task is to check whether two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, “act” and “tac” are an anagram of each other.Input consists of two strings in lowercase english characters.
Constraints:
1 ≤ |s1|, |s2| ≤ 10^5Print "YES" without quotes if the two strings are anagram else print "NO".Sample Input
naman
manan
Sample Output
YES
Explanation: Both String contain 2 'a's, 2 'n's and 1 'm'., I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
#define pu push_back
#define fi first
#define se second
#define mp make_pair
#define int long long
#define pii pair<int,int>
#define mm (s+e)/2
#define all(x) x.begin(), x.end()
#define For(i, st, en) for(int i=st; i<en; i++)
#define tr(x) for(auto it=x.begin(); it!=x.end(); it++)
#define fast std::ios::sync_with_stdio(false);cin.tie(NULL);
#define sz 200000
int A[26],B[26];
signed main()
{
string s,p;
cin>>s>>p;
for(int i=0;i<s.size();i++)
{
int y=s[i]-'a';
A[y]++;
}
for(int i=0;i<p.size();i++)
{
int y=p[i]-'a';
B[y]++;
}int ch=1;
for(int i=0;i<26;i++)
{
if(B[i]!=A[i])ch=0;
}
if(ch==1) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.