Instruction
stringlengths 261
35k
| Response
stringclasses 1
value |
---|---|
For this Question: Given two strings A and B, check if the string A is a sub-string of string B or not.First line of input contains a string A, the second line of the input contains the string B.
Constraints:-
1 < = |A| < = |B| < = 1000
Note:- String will only contain lowercase english letters.Print "Yes" if the string A is the substring of string B, else print "No".Sample Input:-
ewt
newton
Sample Output:-
Yes
Sample Input:-
erf
sdafa
Sample Output:-
No, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
// Returns true if s1 is substring of s2
int isSubstring(string s1, string s2)
{
int M = s1.length();
int N = s2.length();
/* A loop to slide pat[] one by one */
for (int i = 0; i <= N - M; i++) {
int j;
/* For current index i, check for
pattern match */
for (j = 0; j < M; j++)
if (s2[i + j] != s1[j])
break;
if (j == M)
return i;
}
return -1;
}
/* Driver program to test above function */
int main()
{
string s1;
string s2 ;
cin>>s1>>s2;
int res = isSubstring(s1, s2);
if (res == -1)
cout << "No";
else
cout <<"Yes";
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a double linked list consisting of N nodes, your task is to reverse the linked list and return the head of the modified list.<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>Reverse()</b> that takes head node of the linked list as a parameter.
Constraints:
1 <= N <= 10^3
1<=value<=100Return the head of the modified linked list.Input:
6
1 2 3 4 5 6
Output:
6 5 4 3 2 1
Explanation:
After reversing the list, elements are as 6 <-> 5 <-> 4 <-> 3 <-> 2 <-> 1., I have written this Solution Code: public static Node Reverse(Node head) {
Node temp = null;
Node current = head;
while (current != null) {
temp = current.prev;
current.prev = current.next;
current.next = temp;
current = current.prev;
}
if (temp != null) {
head = temp.prev;
}
return head;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A[], of size N containing positive integers. You need to print the elements of an array in increasing order.The first line of the input denotes the number of test cases 'T'. The first line of the test case is the size of the array and the second line consists of array elements.
For Python Users just complete the given function.
<b>Constraints:</b>
1 ≤ T ≤ 100
1 ≤ N ≤ 1000
1 ≤ A[i] ≤ 1000For each testcase print the sorted array in a new line.Input:
2
5
4 1 3 9 7
10
10 9 8 7 6 5 4 3 2 1
Output:
1 3 4 7 9
1 2 3 4 5 6 7 8 9 10
<b>Explanation:</b>
Testcase 1: 1 3 4 7 9 are in sorted form.
Testcase 2: For the given input, 1 2 3 4 5 6 7 8 9 10 are in sorted form., 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;
int a[N];
signed main() {
IOS;
int t; cin >> t;
while(t--){
int n; cin >> n;
for(int i = 1; i <= n; i++)
cin >> a[i];
sort(a + 1, a + n + 1);
for(int i = 1; i <= n; i++)
cout << a[i] << " ";
cout << 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[], of size N containing positive integers. You need to print the elements of an array in increasing order.The first line of the input denotes the number of test cases 'T'. The first line of the test case is the size of the array and the second line consists of array elements.
For Python Users just complete the given function.
<b>Constraints:</b>
1 ≤ T ≤ 100
1 ≤ N ≤ 1000
1 ≤ A[i] ≤ 1000For each testcase print the sorted array in a new line.Input:
2
5
4 1 3 9 7
10
10 9 8 7 6 5 4 3 2 1
Output:
1 3 4 7 9
1 2 3 4 5 6 7 8 9 10
<b>Explanation:</b>
Testcase 1: 1 3 4 7 9 are in sorted form.
Testcase 2: For the given input, 1 2 3 4 5 6 7 8 9 10 are in sorted form., I have written this Solution Code: // arr is unsorted array
// n is the number of elements in the array
function bubbleSort(arr, n) {
// write code here
// do not console.log the answer
// return sorted array
return arr.sort((a, b) => a - b)
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A[], of size N containing positive integers. You need to print the elements of an array in increasing order.The first line of the input denotes the number of test cases 'T'. The first line of the test case is the size of the array and the second line consists of array elements.
For Python Users just complete the given function.
<b>Constraints:</b>
1 ≤ T ≤ 100
1 ≤ N ≤ 1000
1 ≤ A[i] ≤ 1000For each testcase print the sorted array in a new line.Input:
2
5
4 1 3 9 7
10
10 9 8 7 6 5 4 3 2 1
Output:
1 3 4 7 9
1 2 3 4 5 6 7 8 9 10
<b>Explanation:</b>
Testcase 1: 1 3 4 7 9 are in sorted form.
Testcase 2: For the given input, 1 2 3 4 5 6 7 8 9 10 are in sorted form., I have written this Solution Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
int temp;
for(int i=1;i<n;i++){
if(a[i]<a[i-1]){
for(int j=i;j>0;j--){
if(a[j]<a[j-1]){
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
else{
break;
}
}
}
}
for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A[], of size N containing positive integers. You need to print the elements of an array in increasing order.The first line of the input denotes the number of test cases 'T'. The first line of the test case is the size of the array and the second line consists of array elements.
For Python Users just complete the given function.
<b>Constraints:</b>
1 ≤ T ≤ 100
1 ≤ N ≤ 1000
1 ≤ A[i] ≤ 1000For each testcase print the sorted array in a new line.Input:
2
5
4 1 3 9 7
10
10 9 8 7 6 5 4 3 2 1
Output:
1 3 4 7 9
1 2 3 4 5 6 7 8 9 10
<b>Explanation:</b>
Testcase 1: 1 3 4 7 9 are in sorted form.
Testcase 2: For the given input, 1 2 3 4 5 6 7 8 9 10 are in sorted form., I have written this Solution Code: def bubbleSort(arr):
arr.sort()
return arr
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There are some monsters troubling Newton. He wants to get rid of as many monsters as possible.
Coincidentally the monsters also don't like each other. So Newton got an idea and he gathered all the N monsters together in a pit.
Now all the monsters started attacking each other. They all have some health and the health of the i- th monster is H<sub>i</sub>. A monster dies when its health becomes less than 1. When a monster attacks another monster, the health of monster that is attacked is reduced by an amount that is equal to the health of the attacking monster.
Since a single monster will always remain alive in the end, find out the minimum possible health of the last alive monster.The first line of the input contains a single integer N
The second line of the input contains N space separated integers H<sub>1</sub>, H<sub>2</sub>,. ., H<sub>N</sub>Find the minimum possible final health of the last alive monster.<b>Sample Input 1:</b>
4
2 20 10 30
<b>Sample Output 1:</b>
2
<b>Explanation</b>
The first monster will attack and kill all the remaining monsters.
<b>Sample Input 2:</b>
4
5 13 8 20000
<b>Sample Output 2:</b>
1
<b>Sample Input 2:</b>
4
5 5 5 5
<b>Sample Output 2:</b>
5, I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
int main(){
int n; cin>>n;
int g; cin>>g;;
for(int i=1; i<n; i++){
int t; cin>>t;
g = __gcd(t, g);
}
cout<<g;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two strings S1 and S2 you have to make the two strings equal.
To make them equal you can change any character of S1 or S2 to any other lowercase letter.
You can perform this operation at most X number of times.
Find the number of ways to make S1 and S2 equal. Two ways are considered different if the string formed after changes are different in both cases.
As the number of ways can be large compute number of ways modulo 1000000007.First line of input contains S1
Second line of input contains S2
Third line of input contains X.
Constraints
1 <= |S1| <= 100000
|S1| = |S2|
0 <= K <= |S1| +|S2|Output a single integer, the required value modulo 1000000007.Sample input 1
nlbmb
wrbqh
4
Sample output 1
16
Sample input 2
xpc
qve
1
Sample output 2
0, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define ll long long
#define int long long
const int N = 1e5 + 5;
const int MOD = 1e9 + 7;
int pow(int a, int b, int m)
{
int ans=1;
while(b)
{
if(b&1)
ans=(ans*a)%m;
b/=2;
a=(a*a)%m;
}
return ans;
}
int fact[N], invfact[N];
int modinv(int k)
{
return pow(k, MOD-2, MOD);
}
void precompute()
{
fact[0]=fact[1]=1;
for(int i=2;i<N;i++)
{
fact[i]=fact[i-1]*i;
fact[i]%=MOD;
}
invfact[N-1]=modinv(fact[N-1]);
for(int i=N-2;i>=0;i--)
{
invfact[i]=invfact[i+1]*(i+1);
invfact[i]%=MOD;
}
}
int nCr(int x, int y)
{
if(y>x)
return 0;
int num=fact[x];
num*=invfact[y];
num%=MOD;
num*=invfact[x-y];
num%=MOD;
return num;
}
int a, b, x;
string s, t;
int dp[N], pref[N];
int32_t main()
{
precompute();
IOS;
cin >> s >> t;
cin >> x;
for(int i = 0; i < s.length(); i ++)
{
if(s[i] == t[i])
a++;
else
b++;
}
for(int i = 0; i <= b; i++)
{
// dp[i] = no.of changes to b such that i of them are involving changing both
// = bCi * 24^i * 2^(b-i)
int ways = nCr(b, i) * pow(24, i, MOD);
ways %= MOD;
ways *= pow(2, b - i, MOD);
ways %= MOD;
dp[i] = ways;
if(i == 0)
pref[0] = dp[0];
else
{
pref[i] = pref[i - 1] + dp[i];
pref[i] %= MOD;
}
}
for(int i = b + 1; i < N; i++)
pref[i] = pref[i - 1];
int ans = 0;
for(int i = 0; 2 * i + b <= x && i <= a; i++)
{
// 2*i operators to the same characters
// 25^i * aCi
int ways = pow(25, i, MOD) * nCr(a, i);
ways %= MOD;
int gg = x - b - 2 * i; // max no. of changes to b where u change both of them
ways *= pref[gg];
ways %= MOD;
ans += ways;
ans %= MOD;
}
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 a stack of integers and N queries. Your task is to perform these operations:-
<b>push:-</b>this operation will add an element to your current stack.
<b>pop:-</b>remove the element that is on top
<b>top:-</b>print the element which is currently on top of stack
<b>Note:-</b>if the stack is already empty then the pop operation will do nothing and 0 will be printed as a top element of the stack if it is empty.<b>User task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the functions:
<b>push()</b>:- that takes the stack and the integer to be added as a parameter.
<b>pop()</b>:- that takes the stack as parameter.
<b>top()</b> :- that takes the stack as parameter.
<b>Constraints:</b>
1 ≤ N ≤ 10<sup>3</sup>You don't need to print anything else other than in <b>top</b> function in which you require to print the topmost element of your stack in a new line, if the stack is empty you just need to print 0.Input:
7
push 1
push 2
top
pop
top
pop
top
Output:
2
1
0
, I have written this Solution Code:
public static void push (Stack < Integer > st, int x)
{
st.push (x);
}
// Function to pop element from stack
public static void pop (Stack < Integer > st)
{
if (st.isEmpty () == false)
{
int x = st.pop ();
}
}
// Function to return top of stack
public static void top(Stack < Integer > st)
{
int x = 0;
if (st.isEmpty () == false)
{
x = st.peek ();
}
System.out.println (x);
}
, 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: Sky (the blue ranger) wants to replace Jack (the red ranger) from his position. For this, he needs to conquer the entire Base.
The Base can be represented as an M*N grid, and Sky needs to conquer it cell by cell. Sky starts conquering the Base from the cell (1, 1). In each move, he conquers the cell, and moves to an adjacent non- conquered cell (he cannot move if there is no adjacent non- conquered cell). Now, there is a catch, the last cell he needs to conquer is (M, N) so as to complete the quest for the red ranger tag!
Please let us know if Sky can replace Jack by conquering all the cells in the Base.
Note: The diagonal cells are not considered as adjacent cells.The first and the only line of input contains two integers M and N.
Constraints
1 <= M, N <= 1000Output "YES" (without quotes) if Sky can conquer the entire Base to replace Jack, else output "NO" (without quotes).Sample Input
2 2
Sample Output
NO
Explanation
The possible journeys of Sky ending at (2, 2) can be:
(1, 1) - > (1, 2) - > (2, 2)
(1, 1) - > (2, 1) - > (2, 2)
Since, in each of the path that Sky takes, the total cells covered are not 4, hence Sky cannot conquer the entire base.
Sample Input
3 3
Sample Output
YES, 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().split(" ");
int m=Integer.parseInt(s[0]);
int n=Integer.parseInt(s[1]);
if(m%2==0 && n%2==0)
System.out.println("NO");
else
System.out.println("YES");
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sky (the blue ranger) wants to replace Jack (the red ranger) from his position. For this, he needs to conquer the entire Base.
The Base can be represented as an M*N grid, and Sky needs to conquer it cell by cell. Sky starts conquering the Base from the cell (1, 1). In each move, he conquers the cell, and moves to an adjacent non- conquered cell (he cannot move if there is no adjacent non- conquered cell). Now, there is a catch, the last cell he needs to conquer is (M, N) so as to complete the quest for the red ranger tag!
Please let us know if Sky can replace Jack by conquering all the cells in the Base.
Note: The diagonal cells are not considered as adjacent cells.The first and the only line of input contains two integers M and N.
Constraints
1 <= M, N <= 1000Output "YES" (without quotes) if Sky can conquer the entire Base to replace Jack, else output "NO" (without quotes).Sample Input
2 2
Sample Output
NO
Explanation
The possible journeys of Sky ending at (2, 2) can be:
(1, 1) - > (1, 2) - > (2, 2)
(1, 1) - > (2, 1) - > (2, 2)
Since, in each of the path that Sky takes, the total cells covered are not 4, hence Sky cannot conquer the entire base.
Sample Input
3 3
Sample Output
YES, I have written this Solution Code: m,n=map(int, input().split())
if(m%2 or n%2):
print("YES")
else:
print("NO"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Sky (the blue ranger) wants to replace Jack (the red ranger) from his position. For this, he needs to conquer the entire Base.
The Base can be represented as an M*N grid, and Sky needs to conquer it cell by cell. Sky starts conquering the Base from the cell (1, 1). In each move, he conquers the cell, and moves to an adjacent non- conquered cell (he cannot move if there is no adjacent non- conquered cell). Now, there is a catch, the last cell he needs to conquer is (M, N) so as to complete the quest for the red ranger tag!
Please let us know if Sky can replace Jack by conquering all the cells in the Base.
Note: The diagonal cells are not considered as adjacent cells.The first and the only line of input contains two integers M and N.
Constraints
1 <= M, N <= 1000Output "YES" (without quotes) if Sky can conquer the entire Base to replace Jack, else output "NO" (without quotes).Sample Input
2 2
Sample Output
NO
Explanation
The possible journeys of Sky ending at (2, 2) can be:
(1, 1) - > (1, 2) - > (2, 2)
(1, 1) - > (2, 1) - > (2, 2)
Since, in each of the path that Sky takes, the total cells covered are not 4, hence Sky cannot conquer the entire base.
Sample Input
3 3
Sample Output
YES, 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(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 pb push_back
#define ll long long
#define ld long double
#define int long long
#define double long double
#define mp make_pair
#define F first
#define S second
typedef pair<int, int> pii;
typedef vector<int> vi;
#define pi 3.141592653589793238
const int MOD = 1e9+7;
const int INF = 1LL<<60;
const int N = 2e5+5;
// 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
void solve(){
int n, m; cin>>n>>m;
if(n%2 || m%2){
cout<<"YES";
}
else{
cout<<"NO";
}
}
signed main()
{
fast
#ifdef SWAPNIL07
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t=1;
// cin>>t;
while(t--){
solve();
cout<<"\n";
}
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For a certain event, the value of a favorable outcome is A and the total outcome is B. If the probability of this event is represented by p/q where p and q are coprime then what will be the value of p+q.<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>Probability()</b> that takes integers A, and B as arguments.
Constraints:-
1 <= A <= B <= 10000Return the value of p+q.Sample Input:-
4 6
Sample Output:-
5
Sample Input:-
3 5
Sample Output:-
8, I have written this Solution Code: int Probability(int A,int B){
int x=1;
for(int i=2;i<=A;i++){
if(A%i==0 && B%i==0){
x=i;
}
}
A=A/x;
B=B/x;
return A+B;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For a certain event, the value of a favorable outcome is A and the total outcome is B. If the probability of this event is represented by p/q where p and q are coprime then what will be the value of p+q.<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>Probability()</b> that takes integers A, and B as arguments.
Constraints:-
1 <= A <= B <= 10000Return the value of p+q.Sample Input:-
4 6
Sample Output:-
5
Sample Input:-
3 5
Sample Output:-
8, I have written this Solution Code: int Probability(int A,int B){
int x=1;
for(int i=2;i<=A;i++){
if(A%i==0 && B%i==0){
x=i;
}
}
A=A/x;
B=B/x;
return A+B;
}, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For a certain event, the value of a favorable outcome is A and the total outcome is B. If the probability of this event is represented by p/q where p and q are coprime then what will be the value of p+q.<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>Probability()</b> that takes integers A, and B as arguments.
Constraints:-
1 <= A <= B <= 10000Return the value of p+q.Sample Input:-
4 6
Sample Output:-
5
Sample Input:-
3 5
Sample Output:-
8, I have written this Solution Code: static int Probability(int A,int B){
int x=1;
for(int i=2;i<=A;i++){
if(A%i==0 && B%i==0){
x=i;
}
}
A=A/x;
B=B/x;
return A+B;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For a certain event, the value of a favorable outcome is A and the total outcome is B. If the probability of this event is represented by p/q where p and q are coprime then what will be the value of p+q.<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>Probability()</b> that takes integers A, and B as arguments.
Constraints:-
1 <= A <= B <= 10000Return the value of p+q.Sample Input:-
4 6
Sample Output:-
5
Sample Input:-
3 5
Sample Output:-
8, I have written this Solution Code: def Probability(A,B):
x=1
for i in range (2,A+1):
if (A%i==0) and (B%i==0):
x=i
A=A//x
B=B//x
return A+B
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given three distinct positive integers, A, B and C, in the input. Your task is to find their median.
The median of a set of integers is the number at the middle position if they are arranged in ascending order.The input consists of a single line containing three integers A, B and C.
<b> Constraints: </b>
1 ≤ A, B, C ≤ 10<sup>9</sup>
A, B, C are pairwise distinct.
Print a single integer, the median of the given numbers.Sample Input 1:
5 1 3
Sample Output 1:
3
Sample Input 2:
1 2 3
Sample Output 2:
2, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
try{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(r);
String a = in.readLine();
String[] nums = a.split(" ");
long[] l = new long[3];
for(int i=0; i<3; i++){
l[i] = Long.parseLong(nums[i]);
}
Arrays.sort(l);
System.out.print(l[1]);
}
catch(Exception e){
System.out.println(e);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given three distinct positive integers, A, B and C, in the input. Your task is to find their median.
The median of a set of integers is the number at the middle position if they are arranged in ascending order.The input consists of a single line containing three integers A, B and C.
<b> Constraints: </b>
1 ≤ A, B, C ≤ 10<sup>9</sup>
A, B, C are pairwise distinct.
Print a single integer, the median of the given numbers.Sample Input 1:
5 1 3
Sample Output 1:
3
Sample Input 2:
1 2 3
Sample Output 2:
2, I have written this Solution Code:
//#define ASC
//#define DBG_LOCAL
#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 <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// #pragma GCC optimize("Ofast")
// #pragma GCC target("avx,avx2,fma")
#define int long long
// #define int __int128
#define all(X) (X).begin(), (X).end()
#define pb push_back
#define endl '\n'
#define fi first
#define se second
// const int mod = 1e9 + 7;
const int mod=998'244'353;
const long long INF = 2e18 + 10;
// const int INF=1e9+10;
#define readv(x, n) \
vector<int> x(n); \
for (auto &i : x) \
cin >> i;
template <typename T>
using v = vector<T>;
template <typename T>
using vv = vector<vector<T>>;
template <typename T>
using vvv = vector<vector<vector<T>>>;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<vector<int>> vvi;
typedef vector<vector<vector<int>>> vvvi;
typedef vector<vector<vector<vector<int>>>> vvvvi;
typedef vector<vector<double>> vvd;
typedef pair<int, int> pii;
int multiply(int a, int b, int in_mod) { return (int)(1LL * a * b % in_mod); }
int mult_identity(int a) { return 1; }
const double PI = acosl(-1);
auto power(auto a, auto b, const int in_mod)
{
auto prod = mult_identity(a);
auto mult = a % 2;
while (b != 0)
{
if (b % 2)
{
prod = multiply(prod, mult, in_mod);
}
if(b/2)
mult = multiply(mult, mult, in_mod);
b /= 2;
}
return prod;
}
auto mod_inv(auto q, const int in_mod)
{
return power(q, in_mod - 2, in_mod);
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define stp cout << fixed << setprecision(20);
void solv()
{
int A ,B, C;
cin>>A>>B>>C;
vector<int> values;
values.push_back(A);
values.push_back(B);
values.push_back(C);
sort(all(values));
cout<<values[1]<<endl;
}
void solve()
{
int t = 1;
// cin>>t;
for(int i = 1;i<=t;i++)
{
// cout<<"Case #"<<i<<": ";
solv();
}
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cerr.tie(NULL);
#ifndef ONLINE_JUDGE
if (fopen("INPUT.txt", "r"))
{
freopen("INPUT.txt", "r", stdin);
freopen("OUTPUT.txt", "w", stdout);
}
#else
#ifdef ASC
namespace fs = std::filesystem;
std::string path = "./";
string filename;
for (const auto & entry : fs::directory_iterator(path)){
if( entry.path().extension().string() == ".in"){
filename = entry.path().filename().stem().string();
}
}
if(filename != ""){
string input_file = filename +".in";
string output_file = filename +".out";
if (fopen(input_file.c_str(), "r"))
{
freopen(input_file.c_str(), "r", stdin);
freopen(output_file.c_str(), "w", stdout);
}
}
#endif
#endif
// auto clk = clock();
// -------------------------------------Code starts here---------------------------------------------------------------------
signed t = 1;
// cin >> t;
for (signed test = 1; test <= t; test++)
{
// cout<<"Case #"<<test<<": ";
// cout<<endl;
solve();
}
// -------------------------------------Code ends here------------------------------------------------------------------
// clk = clock() - clk;
#ifndef ONLINE_JUDGE
// cerr << fixed << setprecision(6) << "\nTime: " << ((float)clk) / CLOCKS_PER_SEC << "\n";
#endif
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given three distinct positive integers, A, B and C, in the input. Your task is to find their median.
The median of a set of integers is the number at the middle position if they are arranged in ascending order.The input consists of a single line containing three integers A, B and C.
<b> Constraints: </b>
1 ≤ A, B, C ≤ 10<sup>9</sup>
A, B, C are pairwise distinct.
Print a single integer, the median of the given numbers.Sample Input 1:
5 1 3
Sample Output 1:
3
Sample Input 2:
1 2 3
Sample Output 2:
2, I have written this Solution Code: lst = list(map(int, input().split()))
lst.sort()
print(lst[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: 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: As they were totally exhausted with the daily chores, Ketani and Nilswap decided to play a game.They get alternate turns in the game and Ketani starts the game. The game consists of a tree containing N nodes numbered 1 to N. On each turn the person chooses a node of the tree that is not yet numbered. If it's Ketani's turn, he writes an odd number to this node whereas if it's Nilswap's turn, he writes an even number to this node.
After the entire tree has been numbered, all the odd numbered nodes that are adjacent to an even numbered node turn even (instantaneous, no propagation).
If the tree contains any odd number in the end, Ketani wins otherwise Nilswap wins. You need to output the name of the winner.
Note: Initially none of the nodes contains a number. Both players play optimally.The first line of the input contains an integer N, the number of nodes in the tree.
The next N-1 lines contain two integers u, v indicating there is an edge between u and v.
Constraints
2 <= N <= 100000
1 <= u, v <= 100000
u != v
The given edges form a tree.Output a single string, the winner of the game.Sample Input 1
3
1 2
2 3
Sample Output 1
Ketani
Sample Input 2
2
1 2
Sample Output 2
Nilswap
Explanation 1:
-> Ketani writes an odd number to node 2.
-> Nilswap writes an even number to node 3.
-> Ketani writes an odd number to node 1.
-> After this, node 2 converts to an even number. But node 1 is still white. So Ketani wins., 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
vector<int> adj[N];
bool ans;
bool dfs(int u, int par = 0) {
int cnt = 0;
for (auto v: adj[u])
if (v != par)
cnt += dfs(v, u);
if (cnt >= 2) {
ans = true;
return false;
}
return 1 - cnt;
}
signed main(){
#ifdef SWAPNIL07
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
fast
int n; cin >> n;
for (int i = 1; i < n; i++) {
int v, u;
cin >> v >> u;
adj[v].pb(u);
adj[u].pb(v);;
}
ans |= dfs(1);
if(ans){
cout<<"Ketani";
}
else{
cout<<"Nilswap";
}
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, consisting of digits from 1 to 9. You can break the number by adding '+' in between, your have to find the sum of all the numbers that can be formed through this way.
For eg:- N = 256
256 = 256
25 + 6 = 31
2 + 56 = 58
2 + 5 + 6 = 13
sum = 256 + 31 + 58 + 13 = 358The input contains a single integer N.
Constraints:-
1 <= N <= 999999999Print the sum of all the possible numbers.Sample Input:
256
Sample Output:
358
Sample Input:
125
Sample Output:
176, I have written this Solution Code: #include <bits/stdc++.h>
#define uint unsigned int
#define ll long long
#define ull unsigned long long
#define sqr(a) (1LL * (a) * (a))
#define mt(...) " [" << #__VA_ARGS__ << ": " << __VA_ARGS__ << "] "
using namespace std;
const int mod = 1000000007;
const int INF = 0x3f3f3f3f;
const int N = 10;
ll res = 0;
void solve(string &str, int n, int i, ll s, ll last) {
if (i == n) {
res += s;
// cout << mt(s) << '\n';
return;
}
int curr = str[i] - '0';
solve(str, n, i + 1, s + curr, curr);
solve(str, n, i + 1, s - last + last * 10 + curr, last * 10 + curr);
}
int main() {
ios::sync_with_stdio(false); cin.tie(NULL);
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
string str;
cin >> str;
int n = str.size();
// solve(str, n, 1, str[0] - '0', str[0] - '0');
// cout << res << '\n';
ll res = 0;
int maxbit = 1 << n;
for (int mask = 0; mask < maxbit; ++mask) {
ll prev = 0;
ll sum = 0;
for (int t = 0; t < n; ++t) {
if (mask & (1 << t)) {
sum -= prev;
prev = prev * 10 + (str[t] - '0');
sum += prev;
}
else {
prev = str[t] - '0';
sum += prev;
}
}
res += sum;
}
res /= 2;
cout << res << '\n';
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 permutation P of size N. You are also given an integer M. You have to cut the given permutation into M subsegments so that each element belongs to exactly one subsegment. After that you can reorder the subsegments in any order, however, elements belonging to the same subsegment should stay together, and in the same order.
What is the lexicographically smallest permutation you can achieve after reordering?The first line contains two space-separated integers N and M.
The second line contains N space-separated integers – P[1], P[2], ... P[N].
<b>Constraints:</b>
2 ≤ N ≤ 10<sup>5</sup>
1 ≤ M ≤ NPrint a single line containing N integers – the lexicographically smallest permutation achievable.Sample Input 1:
5 4
2 1 4 3 5
Sample Output 1:
1 2 3 5 4
Sample Explanation 1:
The optimal partition of the given permutation will be 2 | 1 | 4 | 3 5. The lexicographically smallest permutation of the subsegments will thus be 1 2 3 5 4.
Sample Input 2:
5 2
2 1 4 3 5
Sample Output 2:
1 4 3 5 2
Sample Explanation 2:
The optimal partition of the given permutation will be 2 | 1 4 3 5. The lexicographically smallest permutation will thus be 1 4 3 5 2., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(long long i=0;i<(long long)(n);i++)
#define REP(i,k,n) for(long long i=k;i<(long long)(n);i++)
#define pb emplace_back
#define lb(v,k) (lower_bound(all(v),(k))-v.begin())
#define ub(v,k) (upper_bound(all(v),(k))-v.begin())
#define fi first
#define se second
#define pi M_PI
#define PQ(T) priority_queue<T>
#define SPQ(T) priority_queue<T,vector<T>,greater<T>>
#define dame(a) {out(a);return 0;}
#define decimal cout<<fixed<<setprecision(15);
#define all(a) a.begin(),a.end()
#define rsort(a) {sort(all(a));reverse(all(a));}
#define dupli(a) {sort(all(a));a.erase(unique(all(a)),a.end());}
#define popcnt __builtin_popcountll
typedef long long ll;
typedef pair<ll,ll> P;
typedef tuple<ll,ll,ll> PP;
typedef tuple<ll,ll,ll,ll> PPP;
using vi=vector<ll>;
using vvi=vector<vi>;
using vvvi=vector<vvi>;
using vvvvi=vector<vvvi>;
using vp=vector<P>;
using vvp=vector<vp>;
using vb=vector<bool>;
using vvb=vector<vb>;
const ll inf=1001001001001001001;
const ll INF=1001001001;
const ll mod=1000000007;
const double eps=1e-10;
template<class T> bool chmin(T&a,T b){if(a>b){a=b;return true;}return false;}
template<class T> bool chmax(T&a,T b){if(a<b){a=b;return true;}return false;}
template<class T> void out(T a){cout<<a<<' ';}
template<class T> void outp(T a){cout<<'('<<a.fi<<','<<a.se<<')'<<'\n';}
template<class T> void outvp(T v){rep(i,v.size())cout<<'('<<v[i].fi<<','<<v[i].se<<')';cout<<'\n';}
template<class T> void outvvp(T v){rep(i,v.size())outvp(v[i]);}
template<class T> void outv(T v){rep(i,v.size()){if(i)cout<<' ';cout<<v[i];}cout<<'\n';}
template<class T> void outvv(T v){rep(i,v.size())outv(v[i]);}
template<class T> bool isin(T x,T l,T r){return (l)<=(x)&&(x)<=(r);}
template<class T> void yesno(T b){if(b)out("yes");else out("no");}
template<class T> void YesNo(T b){if(b)out("Yes");else out("No");}
template<class T> void YESNO(T b){if(b)out("YES");else out("NO");}
template<class T> void outset(T s){auto itr=s.begin();while(itr!=s.end()){if(itr!=s.begin())cout<<' ';cout<<*itr;itr++;}cout<<'\n';}
void outs(ll a,ll b){if(a>=inf-100)out(b);else out(a);}
ll gcd(ll a,ll b){if(b==0)return a;return gcd(b,a%b);}
ll modpow(ll a,ll b){ll res=1;a%=mod;while(b){if(b&1)res=res*a%mod;a=a*a%mod;b>>=1;}return res;}
int main(){
ll n,k;cin>>n>>k;
k--;
vi v(n),rv(n);
vb f(n+1,false);f[0]=f[n]=true;
rep(i,n){
cin>>v[i];v[i]--;
rv[v[i]]=i;
}
if(k == 0)
{
for(int i = 0;i<n;i++)
cout<<v[i]+1<<" ";
return 0 ;
}
ll x=0;
while(x<n){
if(k==0)break;
ll i=rv[x];
if(!f[i]){
f[i]=true;k--;
}
if(k==0)break;
ll r=i;while(r+1<n&&v[r+1]==v[r]+1)r++;
if(!f[r+1]){
if(k==1){
vi srt;
rep(j,n)if(f[j]&&v[j]>=v[i])srt.pb(v[j]);
rsort(srt);
bool done=false;
vb d(n+1,false);
REP(j,v[i],n){
if(done)break;
if(!d[rv[j]]&&!f[rv[j]]){
f[rv[j]]=true;break;
}
if(d[rv[j]])continue;
assert(srt.back()==j);
srt.pop_back();
if(!srt.size())break;
REP(k,rv[j]+1,n){
if(f[k])break;
if(v[k]>srt.back()){
f[k]=true;done=true;break;
}
d[k]=true;
}
}
break;
}
f[r+1]=true;k--;
}
x=v[r]+1;
}
vvi al;
rep(i,n)if(f[i]){
vi tmp;tmp.pb(v[i]);
REP(j,i+1,n){
if(f[j])break;
tmp.pb(v[j]);
}
al.pb(tmp);
}
vi srt;rep(i,al.size())srt.pb(i);
auto cmp=[&](ll a,ll b){
return al[a][0]<al[b][0];
};
sort(all(srt),cmp);
for(ll i:srt)for(ll j:al[i])out(j+1);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Numbers are awesome, larger numbers are more awesome!
Given an array A of size N, you need to find the maximum sum that can be obtained from the elements of the array (the selected elements need not be contiguous). You may even decide to take no element to get a sum of 0.The first line of the input contains the size of the array.
The next line contains N (white-space separated) integers denoting the elements of the array.
<b>Constraints:</b>
1 ≤ N ≤ 10<sup>4</sup>
-10<sup>7</sup> ≤ A[i] ≤10<sup>7</sup>For each test case, output one integer representing the maximum value of the sum that can be obtained using the various elements of the array.Input 1:
5
1 2 1 -1 1
output 1:
5
input 2:
5
0 0 -1 0 0
output 2:
0
<b>Explanation 1:</b>
In order to maximize the sum among [ 1 2 1 -1 1], we need to only consider [ 1 2 1 1] and neglect the [-1]., 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 n; cin >> n;
int sum = 0;
for(int i = 1; i <= n; i++){
int p; cin >> p;
if(p > 0)
sum += p;
}
cout << sum;
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Numbers are awesome, larger numbers are more awesome!
Given an array A of size N, you need to find the maximum sum that can be obtained from the elements of the array (the selected elements need not be contiguous). You may even decide to take no element to get a sum of 0.The first line of the input contains the size of the array.
The next line contains N (white-space separated) integers denoting the elements of the array.
<b>Constraints:</b>
1 ≤ N ≤ 10<sup>4</sup>
-10<sup>7</sup> ≤ A[i] ≤10<sup>7</sup>For each test case, output one integer representing the maximum value of the sum that can be obtained using the various elements of the array.Input 1:
5
1 2 1 -1 1
output 1:
5
input 2:
5
0 0 -1 0 0
output 2:
0
<b>Explanation 1:</b>
In order to maximize the sum among [ 1 2 1 -1 1], we need to only consider [ 1 2 1 1] and neglect the [-1]., I have written this Solution Code: n=int(input())
li = list(map(int,input().strip().split()))
sum=0
for i in li:
if i>0:
sum+=i
print(sum), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Numbers are awesome, larger numbers are more awesome!
Given an array A of size N, you need to find the maximum sum that can be obtained from the elements of the array (the selected elements need not be contiguous). You may even decide to take no element to get a sum of 0.The first line of the input contains the size of the array.
The next line contains N (white-space separated) integers denoting the elements of the array.
<b>Constraints:</b>
1 ≤ N ≤ 10<sup>4</sup>
-10<sup>7</sup> ≤ A[i] ≤10<sup>7</sup>For each test case, output one integer representing the maximum value of the sum that can be obtained using the various elements of the array.Input 1:
5
1 2 1 -1 1
output 1:
5
input 2:
5
0 0 -1 0 0
output 2:
0
<b>Explanation 1:</b>
In order to maximize the sum among [ 1 2 1 -1 1], we need to only consider [ 1 2 1 1] and neglect the [-1]., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
int n = Integer.parseInt(br.readLine());
String str[] = br.readLine().split(" ");
long arr[] = new long[n];
long sum=0;
for(int i=0;i<n;i++){
arr[i] = Integer.parseInt(str[i]);
if(arr[i]>0){
sum+=arr[i];
}
}
System.out.print(sum);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of positive integers. The task is to find inversion count of array.
Inversion Count : For an array, inversion count indicates how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.
Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
Asked in Adobe, Amazon, Microsoft.The first line of each test case is N, the size of the array. The second line of each test case contains N elements.
Constraints:-
1 ≤ N ≤ 10^5
1 ≤ a[i] ≤ 10^5Print the inversion count of array.Sample Input:
5
2 4 1 3 5
Sample Output:
3
Explanation:
Testcase 1: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3)., 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());
String input[]=br.readLine().split("\\s");
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(input[i]);
}
System.out.print(implementMergeSort(a,0,n-1));
}
public static long implementMergeSort(int arr[], int start, int end)
{
long count=0;
if(start<end)
{
int mid=start+(end-start)/2;
count +=implementMergeSort(arr,start,mid);
count +=implementMergeSort(arr,mid+1,end);
count +=merge(arr,start,end,mid);
}
return count;
}
public static long merge(int []a,int start,int end,int mid)
{
int i=start;
int j=mid+1;
int k=0;
int len=end-start+1;
int c[]=new int[len];
long inv_count=0;
while(i<=mid && j<=end)
{
if(a[i]<=a[j])
{
c[k++]=a[i];
i++;
}
else
{
c[k++]=a[j];
j++;
inv_count +=(mid-i)+1;
}
}
while(i<=mid)
{
c[k++]=a[i++];
}
while(j<=end)
{
c[k++]=a[j++];
}
for(int l=0;l<len;l++)
a[start+l]=c[l];
return inv_count;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of positive integers. The task is to find inversion count of array.
Inversion Count : For an array, inversion count indicates how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.
Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
Asked in Adobe, Amazon, Microsoft.The first line of each test case is N, the size of the array. The second line of each test case contains N elements.
Constraints:-
1 ≤ N ≤ 10^5
1 ≤ a[i] ≤ 10^5Print the inversion count of array.Sample Input:
5
2 4 1 3 5
Sample Output:
3
Explanation:
Testcase 1: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3)., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define int long long
long long _mergeSort(int arr[], int temp[], int left, int right);
long long merge(int arr[], int temp[], int left, int mid, int right);
/* This function sorts the input array and returns the
number of inversions in the array */
long long mergeSort(int arr[], int array_size)
{
int temp[array_size];
return _mergeSort(arr, temp, 0, array_size - 1);
}
/* An auxiliary recursive function that sorts the input array and
returns the number of inversions in the array. */
long long _mergeSort(int arr[], int temp[], int left, int right)
{
int mid, inv_count = 0;
if (right > left) {
/* Divide the array into two parts and
call _mergeSortAndCountInv()
for each of the parts */
mid = (right + left) / 2;
/* Inversion count will be sum of
inversions in left-part, right-part
and number of inversions in merging */
inv_count += _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid + 1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid + 1, right);
}
return inv_count;
}
/* This funt merges two sorted arrays
and returns inversion count in the arrays.*/
long long merge(int arr[], int temp[], int left,
int mid, int right)
{
int i, j, k;
long long inv_count = 0;
i = left; /* i is index for left subarray*/
j = mid; /* j is index for right subarray*/
k = left; /* k is index for resultant merged subarray*/
while ((i <= mid - 1) && (j <= right)) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
}
else {
temp[k++] = arr[j++];
/* this is tricky -- see above
explanation/diagram for merge()*/
inv_count = inv_count + (mid - i);
}
}
/* Copy the remaining elements of left subarray
(if there are any) to temp*/
while (i <= mid - 1)
temp[k++] = arr[i++];
/* Copy the remaining elements of right subarray
(if there are any) to temp*/
while (j <= right)
temp[k++] = arr[j++];
/*Copy back the merged elements to original array*/
for (i = left; i <= right; i++)
arr[i] = temp[i];
return inv_count;
}
signed main()
{
int n;
cin>>n;
int a[n];
unordered_map<int,int> m;
for(int i=0;i<n;i++){
cin>>a[i];
if(m.find(a[i])==m.end()){
m[a[i]]=i;
}
}
cout<<mergeSort(a,n);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For a given positive integer N, determine if there exist three <b>positive</b> integers a, b and c such that the following two conditions hold:
1. a + b + c = N
2. a ^ b ^ c = 0 where ^ denotes the bitwise XOR operation.
If there exist such a triple (a, b, c), print the lexicographically smallest one.
Else, print -1.The first line of input contains a single integer, T.
T lines follow, each containing a single integer, N.
<b>Constraints:</b>
1 <= T <= 10<sup>3</sup>
3 <= N <= 10<sup>18</sup>For each test, in a new line, print the lexicographically smallest triple (a, b, c) if it exists, else print -1.Sample Input:
3
3
6
12
Sample Output:
-1
1 2 3
2 4 6, I have written this Solution Code: for _ in range(int(input())):
n = int(input())
if n%2 or n<6:
print(-1)
continue
m = n//2
sl = 1
while m % 2 == 0:
m >>= 1
sl <<= 1
if n == sl*2:
print(-1)
continue
print(sl,n//2-sl,n//2), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For a given positive integer N, determine if there exist three <b>positive</b> integers a, b and c such that the following two conditions hold:
1. a + b + c = N
2. a ^ b ^ c = 0 where ^ denotes the bitwise XOR operation.
If there exist such a triple (a, b, c), print the lexicographically smallest one.
Else, print -1.The first line of input contains a single integer, T.
T lines follow, each containing a single integer, N.
<b>Constraints:</b>
1 <= T <= 10<sup>3</sup>
3 <= N <= 10<sup>18</sup>For each test, in a new line, print the lexicographically smallest triple (a, b, c) if it exists, else print -1.Sample Input:
3
3
6
12
Sample Output:
-1
1 2 3
2 4 6, I have written this Solution Code: //HEADER FILES AND NAMESPACES
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
// #include <sys/resource.h>
using namespace std;
using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename T>
using ordered_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
// PRAGMAS (do these even work?)
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,avx,avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
// DEFINE STATEMENTS
const long long infty = 1e18;
#define num1 1000000007
#define num2 998244353
#define REP(i,a,n) for(ll i=a;i<n;i++)
#define REPd(i,a,n) for(ll i=a; i>=n; i--)
#define pb push_back
#define pob pop_back
#define f first
#define s second
#define fix(f,n) std::fixed<<std::setprecision(n)<<f
#define all(x) x.begin(), x.end()
#define M_PI 3.14159265358979323846
#define epsilon (double)(0.000000001)
#define popcount __builtin_popcountll
#define fileio(x) freopen("input.txt", "r", stdin); freopen(x, "w", stdout);
#define out(x) cout << ((x) ? "Yes\n" : "No\n")
#define sz(x) x.size()
#define start_clock() auto start_time = std::chrono::high_resolution_clock::now();
#define measure() auto end_time = std::chrono::high_resolution_clock::now(); cerr << (end_time - start_time)/std::chrono::milliseconds(1) << "ms" << endl;
typedef long long ll;
typedef long double ld;
typedef vector<long long> vll;
typedef pair<long long, long long> pll;
typedef vector<pair<long long, long long>> vpll;
typedef vector<int> vii;
// DEBUG FUNCTIONS
#ifdef LOCALY
template<typename T>
void __p(T a) {
cout<<a;
}
template<typename T, typename F>
void __p(pair<T, F> a) {
cout<<"{";
__p(a.first);
cout<<",";
__p(a.second);
cout<<"}";
}
template<typename T>
void __p(std::vector<T> a) {
cout<<"{";
for(auto it=a.begin(); it<a.end(); it++)
__p(*it),cout<<",}"[it+1==a.end()];
}
template<typename T>
void __p(std::set<T> a) {
cout<<"{";
for(auto it=a.begin(); it!=a.end();){
__p(*it);
cout<<",}"[++it==a.end()];
}
}
template<typename T>
void __p(std::multiset<T> a) {
cout<<"{";
for(auto it=a.begin(); it!=a.end();){
__p(*it);
cout<<",}"[++it==a.end()];
}
}
template<typename T, typename F>
void __p(std::map<T,F> a) {
cout<<"{\n";
for(auto it=a.begin(); it!=a.end();++it)
{
__p(it->first);
cout << ": ";
__p(it->second);
cout<<"\n";
}
cout << "}\n";
}
template<typename T, typename ...Arg>
void __p(T a1, Arg ...a) {
__p(a1);
__p(a...);
}
template<typename Arg1>
void __f(const char *name, Arg1 &&arg1) {
cout<<name<<" : ";
__p(arg1);
cout<<endl;
}
template<typename Arg1, typename ... Args>
void __f(const char *names, Arg1 &&arg1, Args &&... args) {
int bracket=0,i=0;
for(;; i++)
if(names[i]==','&&bracket==0)
break;
else if(names[i]=='(')
bracket++;
else if(names[i]==')')
bracket--;
const char *comma=names+i;
cout.write(names,comma-names)<<" : ";
__p(arg1);
cout<<" | ";
__f(comma+1,args...);
}
#define trace(...) cout<<"Line:"<<__LINE__<<" ", __f(#__VA_ARGS__, __VA_ARGS__)
#else
#define trace(...)
#define error(...)
#endif
// DEBUG FUNCTIONS END
// CUSTOM HASH TO SPEED UP UNORDERED MAP AND TO AVOID FORCED CLASHES
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); // FOR RANDOM NUMBER GENERATION
ll mod_exp(ll a, ll b, ll c)
{
ll res=1; a=a%c;
while(b>0)
{
if(b%2==1)
res=(res*a)%c;
b/=2;
a=(a*a)%c;
}
return res;
}
ll mymod(ll a,ll b)
{
return (((a = a%b) < 0) ? a + b : a);
}
ll gcdExtended(ll,ll,ll *,ll *);
ll modInverse(ll a, ll m)
{
ll x, y;
ll g = gcdExtended(a, m, &x, &y);
g++; //this line was added just to remove compiler warning
ll res = (x%m + m) % m;
return res;
}
ll gcdExtended(ll a, ll b, ll *x, ll *y)
{
if (a == 0)
{
*x = 0, *y = 1;
return b;
}
ll x1, y1;
ll gcd = gcdExtended(b%a, a, &x1, &y1);
*x = y1 - (b/a) * x1;
*y = x1;
return gcd;
}
struct Graph
{
vector<vector<int>> adj;
Graph(int n)
{
adj.resize(n+1);
}
void add_edge(int a, int b, bool directed = false)
{
adj[a].pb(b);
if(!directed) adj[b].pb(a);
}
};
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin >> t;
REP(i, 0, t)
{
ll n;
cin >> n;
if(n&1) cout << "-1\n";
else
{
ll x = n/2;
vll bits;
REP(i, 0, 60)
{
if((x >> i)&1)
{
bits.pb(i);
}
}
if(bits.size() == 1)
{
cout << "-1\n";
}
else
{
ll a = (1ll << bits[0]);
cout << a << " " << x - a << " " << x << "\n";
}
}
}
return 0;
}
/*
1. Check borderline constraints. Can a variable you are dividing by be 0?
2. Use ll while using bitshifts
3. Do not erase from set while iterating it
4. Initialise everything
5. Read the task carefully, is something unique, sorted, adjacent, guaranteed??
6. DO NOT use if(!mp[x]) if you want to iterate the map later
7. Are you using i in all loops? Are the i's conflicting?
*/
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For a given positive integer N, determine if there exist three <b>positive</b> integers a, b and c such that the following two conditions hold:
1. a + b + c = N
2. a ^ b ^ c = 0 where ^ denotes the bitwise XOR operation.
If there exist such a triple (a, b, c), print the lexicographically smallest one.
Else, print -1.The first line of input contains a single integer, T.
T lines follow, each containing a single integer, N.
<b>Constraints:</b>
1 <= T <= 10<sup>3</sup>
3 <= N <= 10<sup>18</sup>For each test, in a new line, print the lexicographically smallest triple (a, b, c) if it exists, else print -1.Sample Input:
3
3
6
12
Sample Output:
-1
1 2 3
2 4 6, I have written this Solution Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import static java.lang.Math.*;
import static java.lang.System.out;
public class Main {
void solve(){
long n= in.nextLong();
if(n%2==1){
sb.append(-1).append("\n");
}
else{
long cnt=0;
n=n/2;
while(n%2==0){
cnt++;
n=n>>1;
}
long x=(1L<<cnt);
long y=(1L<<cnt);
long z=0;
while(n!=0){
n=n>>1;
cnt++;
if((n&1)==1){
y+=(1L<<cnt);
z+=(1L<<cnt);
}
}
long[] a= new long[3];
a[0]=x;
a[1]=y;
a[2]=z;
sort(a);
if(a[0]!=0){
sb.append(a[0]).append(" ");
sb.append(a[1]).append(" ");
sb.append(a[2]).append("\n");
}
else{
sb.append(-1).append("\n");
}
}
}
FastReader in;
StringBuffer sb;
public static void main(String[] args) {
new Main().run();
}
void run(){
in= new FastReader();
start();
}
void start(){
sb= new StringBuffer();
for(int t=in.nextInt();t>0;t--) {
solve();
}
out.print(sb);
}
void swap( int i , int j) {
int tmp = i;
i = j;
j = tmp;
}
long power(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
int lower_bound(long[] a, long x) {
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
int upper_bound(long[] arr, int key) {
int i=0, j=arr.length-1;
if (arr[j]<=key) return j+1;
if(arr[i]>key) return i;
while (i<j){
int mid= (i+j)/2;
if(arr[mid]<=key){
i= mid+1;
}else{
j=mid;
}
}
return i;
}
void sort(long[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
int[] intArr(int n){
int[] res= new int[n];
for(int i=0;i<n;i++){
res[i]= in.nextInt();
}
return res;
}
long[] longArr(int n){
long[] res= new long[n];
for(int i=0;i<n;i++){
res[i]= in.nextLong();
}
return res;
}
boolean isDigitSumPalindrome(long N) {
long sum= sumOfDigits(String.valueOf(N));
long rev=0;
long org= sum;
while (sum!=0){
long d= sum%10;
rev = rev*10 +d;
sum /= 10;
}
return org == rev;
}
long sumOfDigits(String n){
long sum= 0;
for (char c: n.toCharArray()){
sum += Integer.parseInt(String.valueOf(c));
}
return sum;
}
long[] revArray(long[] arr) {
int n= arr.length;
int i=0, j=n-1;
while (i<j){
long temp= arr[i];
arr[i]= arr[j];
arr[j]= temp;
i++;
j--;
}
return arr;
}
long gcd(long a, long b){
if (b==0)
return a;
return gcd(b, a%b);
}
long lcm(long a,long b){
return (a*b)/gcd(a,b);
}
static class Pair implements Comparable<Pair>{
long first;
long second;
Pair(long x, long y){
this.first=x;
this.second=y;
}
@Override
public int compareTo(Pair o) {
return 0;
}
}
public 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 (Exception e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
float nextFloat(){
return Float.parseFloat(next());
}
String nextLine(){
String str="";
try{
str=br.readLine();
}catch (Exception e){
e.printStackTrace();
}
return str;
}
}
}, In this Programming Language: Java, 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: You are given two integers N and M (N > M). You have to find the smallest integer <b>X</b> such that <i>N - M <= X <= N + M</i> and <i>M - X <= X - N</i>First and the only line of the input contains two integers N and M.
Constraints:
1 <= N < M <= 10<sup>9</sup>Find and print the smallest integer X which satisifes the above condition. If no such integer exists, print -1.Sample Input:
8 4
Sample Output:
6
Explaination:
6 is the smallest integer X between <b>N - M</b> (8 - 4 = 4) and <b>N + M</b> (8 + 4 = 12) such that M - X <= X - N., I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL);
#define int long long
#define pb push_back
#define ff first
#define ss second
#define endl '\n'
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
using T = pair<int, int>;
typedef long long ll;
const int mod = 1e9 + 7;
const int INF = 1e9;
void solve() {
int n, m;
cin >> n >> m;
int y = (n + m + 1)/2;
cout << y;
}
signed main(){
fast
int t = 1;
// cin >> t;
for(int i = 1; i <= t; i++){
solve();
if(i != t) cout << endl;
}
}, 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 arranged in a circular fashion. Your task is to find the maximum contiguous subarray sum containing at least 1 element.The first line of input contains a single integer T which denotes the number of test cases. The first line of each test case contains a single integer N which denotes the total number of elements. The second line of each test case contains N space-separated integers denoting the elements of the array.
<b>Constraints:</b>
1 <= T <= 100
1 <= N <= 10^5
-10^6 <= Arr[i] <= 10^6
The Sum of N over all test cases is less than equal to 10^6.For each test case print the maximum sum obtained by adding the consecutive elements.<b>Input:</b>
4
7
8 -8 9 -9 10 -11 12
8
10 -3 -4 7 6 5 -4 -1
8
-1 40 -14 7 6 5 -4 -1
4
-1 -2 -3 -4
<b>Output:</b>
22
23
52
-1
Explanation:
Testcase 1: Starting from the last element of the array, i.e, 12, and moving in a circular fashion, we have max subarray as 12, 8, -8, 9, -9, 10, which gives the maximum sum as 22., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static long maxSubarraySumCircular(long[] array) {
long currentSum = 0, maxSum = Long.MIN_VALUE;
for(int i = 0; i < array.length; i++) {
currentSum = Math.max(currentSum + array[i], array[i]);
maxSum = Math.max(maxSum, currentSum);
}
if(maxSum < 0) return maxSum;
currentSum = 0;
long minSum = Long.MAX_VALUE;
for(int i = 0; i < array.length; i++) {
currentSum = Math.min(currentSum + array[i], array[i]);
minSum = Math.min(minSum, currentSum);
}
long totalSum = 0;
for(long element : array) totalSum += element;
return Math.max(maxSum, totalSum - minSum);
}
public static void main (String[] args) {
FastReader sc = new FastReader();
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
long a[] = new long[n];
long sum = 0l;
for(int i=0;i<n;i++){
a[i] = sc.nextLong();
}
System.out.println(maxSubarraySumCircular(a));
}
}
}, 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 arranged in a circular fashion. Your task is to find the maximum contiguous subarray sum containing at least 1 element.The first line of input contains a single integer T which denotes the number of test cases. The first line of each test case contains a single integer N which denotes the total number of elements. The second line of each test case contains N space-separated integers denoting the elements of the array.
<b>Constraints:</b>
1 <= T <= 100
1 <= N <= 10^5
-10^6 <= Arr[i] <= 10^6
The Sum of N over all test cases is less than equal to 10^6.For each test case print the maximum sum obtained by adding the consecutive elements.<b>Input:</b>
4
7
8 -8 9 -9 10 -11 12
8
10 -3 -4 7 6 5 -4 -1
8
-1 40 -14 7 6 5 -4 -1
4
-1 -2 -3 -4
<b>Output:</b>
22
23
52
-1
Explanation:
Testcase 1: Starting from the last element of the array, i.e, 12, and moving in a circular fashion, we have max subarray as 12, 8, -8, 9, -9, 10, which gives the maximum sum as 22., I have written this Solution Code: def kadane(a):
Max = a[0]
temp = Max
for i in range(1,len(a)):
temp += a[i]
if temp < a[i]:
temp = a[i]
Max = max(Max,temp)
return Max
def maxCircularSum(a):
n = len(a)
max_kadane = kadane(a)
neg_a = [-1*x for x in a]
max_neg_kadane = kadane(neg_a)
max_wrap = -(sum(neg_a)-max_neg_kadane)
res = max(max_wrap,max_kadane)
return res if res != 0 else max_kadane
for _ in range(int(input())):
s=int(input())
a=list(map(int,input().split()))
print(maxCircularSum(a)), 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 arranged in a circular fashion. Your task is to find the maximum contiguous subarray sum containing at least 1 element.The first line of input contains a single integer T which denotes the number of test cases. The first line of each test case contains a single integer N which denotes the total number of elements. The second line of each test case contains N space-separated integers denoting the elements of the array.
<b>Constraints:</b>
1 <= T <= 100
1 <= N <= 10^5
-10^6 <= Arr[i] <= 10^6
The Sum of N over all test cases is less than equal to 10^6.For each test case print the maximum sum obtained by adding the consecutive elements.<b>Input:</b>
4
7
8 -8 9 -9 10 -11 12
8
10 -3 -4 7 6 5 -4 -1
8
-1 40 -14 7 6 5 -4 -1
4
-1 -2 -3 -4
<b>Output:</b>
22
23
52
-1
Explanation:
Testcase 1: Starting from the last element of the array, i.e, 12, and moving in a circular fashion, we have max subarray as 12, 8, -8, 9, -9, 10, which gives the maximum sum as 22., 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 EPS 1e-9
#define PI 3.1415926535897932384626433832795
#define max1 10001
#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
void fast(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int INF = 4557430888798830399ll;
signed main()
{
fast();
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> A(n);
FOR(i,n){
cin>>A[i];
}
int maxTillNow = -INF;
int maxEndingHere = -INF;
int start = 0;
while (start < A.size()) {
maxEndingHere = max(maxEndingHere + A[start], (int)A[start]);
maxTillNow = max(maxTillNow, maxEndingHere);
start++;
}
vector<int> prefix(n, 0), suffix(n, 0), maxSuffTill(n, 0);
for (int i = 0; i < n; ++i) {
prefix[i] = A[i];
if (i != 0) prefix[i] += prefix[i - 1];
}
for (int i = n - 1; i >= 0; --i) {
suffix[i] = A[i];
maxSuffTill[i] = max(A[i],(int) 0);
if (i != n - 1) {
suffix[i] += suffix[i + 1];
maxSuffTill[i] = max(suffix[i], maxSuffTill[i + 1]);
}
}
for (int i = 0; i < n; ++i) {
int sum = prefix[i];
if (i != n - 1) sum += maxSuffTill[i + 1];
maxTillNow = max(maxTillNow, sum);
}
out(maxTillNow);
}}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given an array and Q queries. Your task is to perform these operations:-
enqueue: this operation will add an element to your current queue.
dequeue: this operation will delete the element from the starting of the queue
displayfront: this operation will print the element presented at the frontUser task:
Since this will be a functional problem, you don't have to take input. You just have to complete the functions:
<b>enqueue()</b>:- that takes the integer to be added and the maximum size of array as parameter.
<b>dequeue()</b>:- that takes the queue as parameter.
<b>displayfront()</b> :- that takes the queue as parameter.
Constraints:
1 <= Q(Number of queries) <= 10<sup>3</sup>
<b> Custom Input:</b>
First line of input should contains two integer number of queries Q and the size of the array N. Next Q lines contains any of the given three operations:-
enqueue x
dequeue
displayfrontDuring a dequeue operation if queue is empty you need to print "Queue is empty", during enqueue operation if the maximum size of array is reached you need to print "Queue is full" and during displayfront operation you need to print the element which is at the front and if the queue is empty you need to print "Queue is empty".
Note:-Each msg or element is to be printed on a new line
Sample Input:-
8 2
displayfront
enqueue 2
displayfront
enqueue 4
displayfront
dequeue
displayfront
enqueue 5
Sample Output:-
Queue is empty
2
2
4
Queue is full
Explanation:-here size of given array is 2 so when last enqueue operation perfomed the array was already full so we display the msg "Queue is full".
Sample input:
5 5
enqueue 4
enqueue 5
displayfront
dequeue
displayfront
Sample output:-
4
5, I have written this Solution Code: public static void enqueue(int x,int k)
{
if (rear >= k) {
System.out.println("Queue is full");
}
else {
a[rear] = x;
rear++;
}
}
public static void dequeue()
{
if (rear <= front) {
System.out.println("Queue is empty");
}
else {
front++;
}
}
public static void displayfront()
{
if (rear<=front) {
System.out.println("Queue is empty");
}
else {
int x = a[front];
System.out.println(x);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A[] of size N containing non-negative integers. You have to move all 0's to the end of array while maintaining the relative order of the non-zero elements.
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.The first line of input line contains T, denoting the number of testcases. Each test cases contains 2 lines. First-line contains N, size of array. Second-line contains elements of array separated by space.
Constraints:
1 <= T <= 100
1 <= N <= 10^5
1 <= A[i] <= 10^5
<b>Sum of N over all testcases does not exceed 10^6</b>
For each testcase you need to print the updated array.Sample Input:
2
5
0 1 0 3 12
8
0 0 0 0 1 2 3 4
Sample Output:
1 3 12 0 0
1 2 3 4 0 0 0 0, I have written this Solution Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int t;
t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
int j=-1;
for(int i=0;i<n;i++){
if(a[i]==0 && j==-1){
j=i;
}
if(j!=-1 && a[i]!=0){
a[j]=a[i];
a[i]=0;
j++;
}
}
for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A[] of size N containing non-negative integers. You have to move all 0's to the end of array while maintaining the relative order of the non-zero elements.
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.The first line of input line contains T, denoting the number of testcases. Each test cases contains 2 lines. First-line contains N, size of array. Second-line contains elements of array separated by space.
Constraints:
1 <= T <= 100
1 <= N <= 10^5
1 <= A[i] <= 10^5
<b>Sum of N over all testcases does not exceed 10^6</b>
For each testcase you need to print the updated array.Sample Input:
2
5
0 1 0 3 12
8
0 0 0 0 1 2 3 4
Sample Output:
1 3 12 0 0
1 2 3 4 0 0 0 0, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n,k;
cin>>n;
int a[n];
int cnt=0;
for(int i=0;i<n;i++){
cin>>a[i];\
if(a[i]==0){cnt++;}
}
for(int i=0;i<n;i++){
if(a[i]!=0){
cout<<a[i]<<" ";
}
}
while(cnt--){
cout<<0<<" ";
}
cout<<endl;
}
}
, 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: You are given a number n. Your task is to print the number of prime numbers before that number.The first line of the number of test cases T.
Next T lines contains the value of N.
<b>Constraints</b>
1 <= T <= 100
1 <= N <= 1000Print the number of primes numbers before that number.Sample Input 1:
3
10
19
4
Sample Output 1:
4
8
2, I have written this Solution Code: n = 1000
arr = [True for i in range(n+1)]
i = 2
while i*i <= n:
if arr[i] == True:
for j in range(i*2, n+1, i):
arr[j] = False
i +=1
arr2 = [0] * (n+1)
for i in range(2,n+1):
if arr[i]:
arr2[i] = arr2[i-1] + 1
else:
arr2[i] = arr2[i-1]
x = int(input())
for i in range(x):
y = int(input())
print(arr2[y]), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a number n. Your task is to print the number of prime numbers before that number.The first line of the number of test cases T.
Next T lines contains the value of N.
<b>Constraints</b>
1 <= T <= 100
1 <= N <= 1000Print the number of primes numbers before that number.Sample Input 1:
3
10
19
4
Sample Output 1:
4
8
2, 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 an integer <b>N</b>, you need to typecast this integer to String. If the typecasting is done successfully then we will print "<b>Nice Job</b>" otherwise "<b>Wrong answer</b>".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>checkConvertion()</b>, which contains N as a parameter.You need to return the typecasted string value. The driver code will print "<b>Nice Job</b>" otherwise "<b>Wrong answer</b>".Sample Input:
5
Sample Output:
Nice Job
Sample Input:
6
Sample Output:
Nice Job, I have written this Solution Code: def checkConevrtion(a):
return str(a)
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer <b>N</b>, you need to typecast this integer to String. If the typecasting is done successfully then we will print "<b>Nice Job</b>" otherwise "<b>Wrong answer</b>".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>checkConvertion()</b>, which contains N as a parameter.You need to return the typecasted string value. The driver code will print "<b>Nice Job</b>" otherwise "<b>Wrong answer</b>".Sample Input:
5
Sample Output:
Nice Job
Sample Input:
6
Sample Output:
Nice Job, I have written this Solution Code: static String checkConevrtion(int a)
{
return String.valueOf(a);
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Walter white is considered very intelligent person. He has a problem to solve. As he is suffering from cancer, can you help him solve it?
Given two integer arrays C and S of length c and s respectively. Index i of array S can be considered good if a subarray of length c can be formed starting from index i which is complimentary to array C.
Two arrays A, B of same length are considered complimentary if any cyclic permutation of A satisfies the property (A[i]- A[i-1]=B[i]-B[i-1]) for all i from 2 to length of A (1 indexing).
Calculate number of good positions in S .
<a href="https://mathworld.wolfram.com/CyclicPermutation.html">Cyclic Permutation</a>
1 2 3 4 has 4 cyclic permutations 2 3 4 1, 3 4 1 2, 4 1 2 3,1 2 3 4First line contains integer s (length of array S).
Second line contains s space separated integers of array S.
Third line contain integer c (length of array C).
Forth line contains c space separated integers of array C.
Constraints:
1 <= s <=1000000
1 <= c <=1000000
1 <= S[i], C[i] <= 10^9
Print the answer.
Input :
9
1 2 3 1 2 4 1 2 3
3
1 2 3
Output :
4
Explanation :
index 1- 1 2 3 matches with 1 2 3
index 2- 2 3 1 matches with 2 3 1(2 3 1 is cyclic permutation of 1 2 3)
index 3- 3 1 2 matches with 3 1 2(3 1 2 is cyclic permutation of 1 2 3)
index 7- 1 2 3 matches with 1 2 3
Input :
4
3 4 3 4
2
1 2
Output :
3
, 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 2000015
#define qw1 freopen("input1.txt", "r", stdin); freopen("output1.txt", "w", stdout);
#define qw2 freopen("input2.txt", "r", stdin); freopen("output2.txt", "w", stdout);
#define qw3 freopen("input3.txt", "r", stdin); freopen("output3.txt", "w", stdout);
#define qw4 freopen("input4.txt", "r", stdin); freopen("output4.txt", "w", stdout);
#define qw5 freopen("input5.txt", "r", stdin); freopen("output5.txt", "w", stdout);
#define qw6 freopen("input6.txt", "r", stdin); freopen("output6.txt", "w", stdout);
#define qw freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
int A[sz],B[sz],C[sz],D[sz],E[sz],F[sz],G[sz];
int n,m;
signed main()
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>A[i];
F[i]=A[i];
}
cin>>m;
for(int i=0;i<m;i++)
{
cin>>B[i];
G[i]=B[i];
C[m-i-1]=B[i];
}
C[m]=-500000000;
for(int i=0;i<n;i++)
{
C[i+m+1]=A[n-i-1];
}
int l=0,r=0;
for(int i=1;i<=n+m;i++)
{
if(i<=r)
{
E[i]=min(r-i+1,E[i-l]);
}
while(i+E[i]<=n+m && C[E[i]]-C[0]==C[i+E[i]]-C[i])
E[i]++;
if(i+E[i]-1>r) {
l=i;r=i+E[i]-1;
}
}
for(int i=0;i<m;i++)
{
C[i]=B[i];
}
for(int i=0;i<n;i++)
{
C[i+m+1]=A[i];
}
for(int i=0;i<n;i++)
{
A[i]=E[n+m-i];
}
l=0;
r=0;
for(int i=1;i<=n+m;i++)
{
if(i<=r)
{
D[i]=min(r-i+1,D[i-l]);
}
while(i+D[i]<=n+m && C[D[i]]-C[0]==C[i+D[i]]-C[i])
D[i]++;
if(i+D[i]-1>r) {
l=i;r=i+D[i]-1;
}
}
// cout<<0<<" ";
for(int i=0;i<n;i++)
{
B[i]=D[i+m+1];
// cout<<A[i]<<" ";
}
// cout<<endl;
// for(int i=0;i<n;i++)
// {
// cout<<B[i]<<" ";
// }cout<<endl;
// for(int i=0;i<=n;i++)
// {
// cout<<i<<" ";
// }
// cout<<endl;
int cnt=0;
vector<pii> xx,yy;
for(int i=0;i<=n;i++){
int a=0;
int b=0;
if(i>0) a=A[i-1];
if(i<n) b=B[i];
// cout<<i<<" "<<a<<" "<<b<<endl;
if(a+b>=m && (a==0 || b==0 ||(F[i]-F[i-1]==G[0]-G[m-1])))
{xx.pu(mp(i-a,i+b-m)); }
if(a==m) xx.pu(mp(i-a,i-a));
if(b==m ) xx.pu(mp(i,i));
}
sort(xx.begin(),xx.end());
for(int i=0;i<xx.size();i++)
{ // cout<<xx[i].fi<<" "<<xx[i].se<<endl;
if(yy.size()==0) yy.pu(mp(xx[i].fi,xx[i].se));
else{
int p=yy.size()-1;
// cout<<i<<" "<<xx[i].fi<<" "<<xx[i].se<<" " <<yy[p].se<<endl;
if(yy[p].se>=xx[i].se) continue;
if(yy[p].se>=xx[i].fi) yy[p].se=xx[i].se;
else yy.pu(mp(xx[i].fi,xx[i].se));
}
}
for(int i=0;i<yy.size();i++)
{ // cout<<yy[i].fi<<" "<<yy[i].se<<endl;
cnt+=yy[i].se-yy[i].fi+1;
}
cout<<cnt<<endl;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, give the number with maximum frequency. If multiple numbers have maximum frequency print the maximum number among them.The first line of the input contains an integer N, and the Second line contains N space-separated integers of the array.
<b>Constraints:</b>
3 <= N <= 1000
1 <= Arr[i] <= 100The output should contain single integer, the number with maximum frequency.If multiple numbers have maximum frequency print the maximum number among them.Sample Input
5
1 4 2 4 5
Sample Output
4
<b>Explanation:-</b>
4 has max frequency=2, 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());
String [] str=br.readLine().trim().split(" ");
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(str[i]);
}
Arrays.sort(a);
int size=a[n-1]+1;
int c[]=new int[size];
for(int i=0;i<size;i++) c[i]=0;
for(int i=0;i<n;i++) c[a[i]]++;
int max=0,freq=c[1];
for(int i=2;i<size;i++){
if(freq<=c[i]){
freq=c[i];
max=i;
}
}
System.out.println(max);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, give the number with maximum frequency. If multiple numbers have maximum frequency print the maximum number among them.The first line of the input contains an integer N, and the Second line contains N space-separated integers of the array.
<b>Constraints:</b>
3 <= N <= 1000
1 <= Arr[i] <= 100The output should contain single integer, the number with maximum frequency.If multiple numbers have maximum frequency print the maximum number among them.Sample Input
5
1 4 2 4 5
Sample Output
4
<b>Explanation:-</b>
4 has max frequency=2, I have written this Solution Code: n = int(input())
a = [int(x) for x in input().split()]
freq = {}
for x in a:
if x not in freq:
freq[x] = 1
else:
freq[x] += 1
mx = max(freq.values())
rf = sorted(freq)
for i in range(len(rf) - 1, -1, -1):
if freq[rf[i]] == mx:
print(rf[i])
break, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, give the number with maximum frequency. If multiple numbers have maximum frequency print the maximum number among them.The first line of the input contains an integer N, and the Second line contains N space-separated integers of the array.
<b>Constraints:</b>
3 <= N <= 1000
1 <= Arr[i] <= 100The output should contain single integer, the number with maximum frequency.If multiple numbers have maximum frequency print the maximum number among them.Sample Input
5
1 4 2 4 5
Sample Output
4
<b>Explanation:-</b>
4 has max frequency=2, 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;
int a[N];
signed main() {
IOS;
int n; cin >> n;
for(int i = 1; i <= n; i++){
int p; cin >> p;
a[p]++;
}
int mx = 0, id = -1;
for(int i = 1; i <= 100; i++){
if(a[i] >= mx)
mx = a[i], id = i;
}
cout << id;
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 positive integers. The task is to find inversion count of array.
Inversion Count : For an array, inversion count indicates how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.
Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
Asked in Adobe, Amazon, Microsoft.The first line of each test case is N, the size of the array. The second line of each test case contains N elements.
Constraints:-
1 ≤ N ≤ 10^5
1 ≤ a[i] ≤ 10^5Print the inversion count of array.Sample Input:
5
2 4 1 3 5
Sample Output:
3
Explanation:
Testcase 1: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3)., 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());
String input[]=br.readLine().split("\\s");
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(input[i]);
}
System.out.print(implementMergeSort(a,0,n-1));
}
public static long implementMergeSort(int arr[], int start, int end)
{
long count=0;
if(start<end)
{
int mid=start+(end-start)/2;
count +=implementMergeSort(arr,start,mid);
count +=implementMergeSort(arr,mid+1,end);
count +=merge(arr,start,end,mid);
}
return count;
}
public static long merge(int []a,int start,int end,int mid)
{
int i=start;
int j=mid+1;
int k=0;
int len=end-start+1;
int c[]=new int[len];
long inv_count=0;
while(i<=mid && j<=end)
{
if(a[i]<=a[j])
{
c[k++]=a[i];
i++;
}
else
{
c[k++]=a[j];
j++;
inv_count +=(mid-i)+1;
}
}
while(i<=mid)
{
c[k++]=a[i++];
}
while(j<=end)
{
c[k++]=a[j++];
}
for(int l=0;l<len;l++)
a[start+l]=c[l];
return inv_count;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of positive integers. The task is to find inversion count of array.
Inversion Count : For an array, inversion count indicates how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.
Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
Asked in Adobe, Amazon, Microsoft.The first line of each test case is N, the size of the array. The second line of each test case contains N elements.
Constraints:-
1 ≤ N ≤ 10^5
1 ≤ a[i] ≤ 10^5Print the inversion count of array.Sample Input:
5
2 4 1 3 5
Sample Output:
3
Explanation:
Testcase 1: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3)., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define int long long
long long _mergeSort(int arr[], int temp[], int left, int right);
long long merge(int arr[], int temp[], int left, int mid, int right);
/* This function sorts the input array and returns the
number of inversions in the array */
long long mergeSort(int arr[], int array_size)
{
int temp[array_size];
return _mergeSort(arr, temp, 0, array_size - 1);
}
/* An auxiliary recursive function that sorts the input array and
returns the number of inversions in the array. */
long long _mergeSort(int arr[], int temp[], int left, int right)
{
int mid, inv_count = 0;
if (right > left) {
/* Divide the array into two parts and
call _mergeSortAndCountInv()
for each of the parts */
mid = (right + left) / 2;
/* Inversion count will be sum of
inversions in left-part, right-part
and number of inversions in merging */
inv_count += _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid + 1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid + 1, right);
}
return inv_count;
}
/* This funt merges two sorted arrays
and returns inversion count in the arrays.*/
long long merge(int arr[], int temp[], int left,
int mid, int right)
{
int i, j, k;
long long inv_count = 0;
i = left; /* i is index for left subarray*/
j = mid; /* j is index for right subarray*/
k = left; /* k is index for resultant merged subarray*/
while ((i <= mid - 1) && (j <= right)) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
}
else {
temp[k++] = arr[j++];
/* this is tricky -- see above
explanation/diagram for merge()*/
inv_count = inv_count + (mid - i);
}
}
/* Copy the remaining elements of left subarray
(if there are any) to temp*/
while (i <= mid - 1)
temp[k++] = arr[i++];
/* Copy the remaining elements of right subarray
(if there are any) to temp*/
while (j <= right)
temp[k++] = arr[j++];
/*Copy back the merged elements to original array*/
for (i = left; i <= right; i++)
arr[i] = temp[i];
return inv_count;
}
signed main()
{
int n;
cin>>n;
int a[n];
unordered_map<int,int> m;
for(int i=0;i<n;i++){
cin>>a[i];
if(m.find(a[i])==m.end()){
m[a[i]]=i;
}
}
cout<<mergeSort(a,n);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S (containing only letters of the English alphabet), find all the capital letters in it (in exactly same order as the string)
Note:- It is guaranteed that the given string will contain at least one capital.Input contains a single line containing the string S.
Constraints:-
1 <= |S| <= 100Print all capital letters present in the string separated by space, in the order of their appearance in the main string.Sample input:-
AbcdEF
Sample Output:-
A E F
Sample Input:-
NewtonSchool
Sample Output:-
N S, I have written this Solution Code: n=input()
for element in n:
if element.isupper():
print(element,end=" "), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string S (containing only letters of the English alphabet), find all the capital letters in it (in exactly same order as the string)
Note:- It is guaranteed that the given string will contain at least one capital.Input contains a single line containing the string S.
Constraints:-
1 <= |S| <= 100Print all capital letters present in the string separated by space, in the order of their appearance in the main string.Sample input:-
AbcdEF
Sample Output:-
A E F
Sample Input:-
NewtonSchool
Sample Output:-
N S, 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 1000001
#define MOD 1000000000000007
#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 cnt[max1];
signed main(){
string s;
cin>>s;
int n=s.length();
//out(s);
FOR(i,n){
if(s[i]>='A' && s[i]<='Z'){
out1(s[i]);
}
}
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 (containing only letters of the English alphabet), find all the capital letters in it (in exactly same order as the string)
Note:- It is guaranteed that the given string will contain at least one capital.Input contains a single line containing the string S.
Constraints:-
1 <= |S| <= 100Print all capital letters present in the string separated by space, in the order of their appearance in the main string.Sample input:-
AbcdEF
Sample Output:-
A E F
Sample Input:-
NewtonSchool
Sample Output:-
N S, I have written this Solution Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
String s = sc.next();
int n = s.length();
for(int i=0;i<n;i++){
if(s.charAt(i)>='A' && s.charAt(i)<='Z'){
System.out.print(s.charAt(i)+" ");
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, give the number with maximum frequency. If multiple numbers have maximum frequency print the maximum number among them.The first line of the input contains an integer N, and the Second line contains N space-separated integers of the array.
<b>Constraints:</b>
3 <= N <= 1000
1 <= Arr[i] <= 100The output should contain single integer, the number with maximum frequency.If multiple numbers have maximum frequency print the maximum number among them.Sample Input
5
1 4 2 4 5
Sample Output
4
<b>Explanation:-</b>
4 has max frequency=2, 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());
String [] str=br.readLine().trim().split(" ");
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(str[i]);
}
Arrays.sort(a);
int size=a[n-1]+1;
int c[]=new int[size];
for(int i=0;i<size;i++) c[i]=0;
for(int i=0;i<n;i++) c[a[i]]++;
int max=0,freq=c[1];
for(int i=2;i<size;i++){
if(freq<=c[i]){
freq=c[i];
max=i;
}
}
System.out.println(max);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, give the number with maximum frequency. If multiple numbers have maximum frequency print the maximum number among them.The first line of the input contains an integer N, and the Second line contains N space-separated integers of the array.
<b>Constraints:</b>
3 <= N <= 1000
1 <= Arr[i] <= 100The output should contain single integer, the number with maximum frequency.If multiple numbers have maximum frequency print the maximum number among them.Sample Input
5
1 4 2 4 5
Sample Output
4
<b>Explanation:-</b>
4 has max frequency=2, I have written this Solution Code: n = int(input())
a = [int(x) for x in input().split()]
freq = {}
for x in a:
if x not in freq:
freq[x] = 1
else:
freq[x] += 1
mx = max(freq.values())
rf = sorted(freq)
for i in range(len(rf) - 1, -1, -1):
if freq[rf[i]] == mx:
print(rf[i])
break, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, give the number with maximum frequency. If multiple numbers have maximum frequency print the maximum number among them.The first line of the input contains an integer N, and the Second line contains N space-separated integers of the array.
<b>Constraints:</b>
3 <= N <= 1000
1 <= Arr[i] <= 100The output should contain single integer, the number with maximum frequency.If multiple numbers have maximum frequency print the maximum number among them.Sample Input
5
1 4 2 4 5
Sample Output
4
<b>Explanation:-</b>
4 has max frequency=2, 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;
int a[N];
signed main() {
IOS;
int n; cin >> n;
for(int i = 1; i <= n; i++){
int p; cin >> p;
a[p]++;
}
int mx = 0, id = -1;
for(int i = 1; i <= 100; i++){
if(a[i] >= mx)
mx = a[i], id = i;
}
cout << id;
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: Tono loves to do shopping. Today, she went to the market where there are N different types of products. She wants to buy exactly K of them at the minimum cost. Although she is super smart, she wants to check your smartness as well. Can you tell her the minimum cost required to buy exactly K products if she has already decided to buy product J?
<b>Note:</b> Tono does not buy the same product twice, and Tono will definitely buy product J (J is the <b>index</b> of the item).The first line of the input contains three integers, N, K, and J, denoting the number of products in the market, the number of products Tono needs to buy, and the product that Tono will definitely buy.
The next line contains N singly spaced integers, the cost of the N products C[1], C[2], ..., C[N].
<b>Constraints:</b>
1 <= N <= 200000
1 <= K <= N
1 <= J <= N
1 <= C[i] <= 1000
Output a single integer, the minimum amount Tono needs to pay.Sample Input 1:
5 3 4
1 2 3 4 5
Sample Output 1:
7
Sample Input 2:
5 1 3
2 4 3 1 1
Sample Output 2:
3
<b>Explanation:</b>
Tono needs to buy exactly 3 products, and she will definitely buy the 4th product. Thus, she will buy the 1st, 2nd, and the 4th product. The total cost she pays is 1+2+4=7.
, I have written this Solution Code: import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
int n = io.nextInt(), k = io.nextInt(), j = io.nextInt() - 1;
int[] arr = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = io.nextInt();
}
int cost = arr[j];
arr[j] = Integer.MAX_VALUE;
Arrays.sort(arr);
for(int i = 0; i < k - 1; i++) {
cost += arr[i];
}
io.println(cost);
io.close();
}
static IO io = new IO();
static class IO {
private byte[] buf;
private InputStream in;
private PrintWriter pw;
private int total, index;
public IO() {
buf = new byte[1024];
in = System.in;
pw = new PrintWriter(System.out);
}
public int next() throws IOException {
if(total < 0)
throw new InputMismatchException();
if(index >= total) {
index = 0;
total = in.read(buf);
if(total <= 0)
return -1;
}
return buf[index++];
}
public int nextInt() throws IOException {
int n = next(), integer = 0;
while(isWhiteSpace(n))
n = next();
int neg = 1;
if(n == '-') {
neg = -1;
n = next();
}
while(!isWhiteSpace(n)) {
if(n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = next();
}
else
throw new InputMismatchException();
}
return neg * integer;
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for(int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public long nextLong() throws IOException {
long integer = 0l;
int n = next();
while(isWhiteSpace(n))
n = next();
int neg = 1;
if(n == '-') {
neg = -1;
n = next();
}
while(!isWhiteSpace(n)) {
if(n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = next();
}
else
throw new InputMismatchException();
}
return neg * integer;
}
public double nextDouble() throws IOException {
double doub = 0;
int n = next();
while(isWhiteSpace(n))
n = next();
int neg = 1;
if(n == '-') {
neg = -1;
n = next();
}
while(!isWhiteSpace(n) && n != '.') {
if(n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = next();
}
else
throw new InputMismatchException();
}
if(n == '.') {
n = next();
double temp = 1;
while(!isWhiteSpace(n)) {
if(n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = next();
}
else
throw new InputMismatchException();
}
}
return doub * neg;
}
public String nextString() throws IOException {
StringBuilder sb = new StringBuilder();
int n = next();
while(isWhiteSpace(n))
n = next();
while(!isWhiteSpace(n)) {
sb.append((char)n);
n = next();
}
return sb.toString();
}
public String nextLine() throws IOException {
int n = next();
while(isWhiteSpace(n))
n = next();
StringBuilder sb = new StringBuilder();
while(!isEndOfLine(n)) {
sb.append((char)n);
n = next();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
return n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1;
}
private boolean isEndOfLine(int n) {
return n == '\n' || n == '\r' || n == -1;
}
public void print(Object obj) {
pw.print(obj);
}
public void println(Object... obj) {
if(obj.length == 1)
pw.println(obj[0]);
else {
for(Object o: obj)
pw.print(o + " ");
pw.println();
}
}
public void flush() throws IOException {
pw.flush();
}
public void close() throws IOException {
pw.close();
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Tono loves to do shopping. Today, she went to the market where there are N different types of products. She wants to buy exactly K of them at the minimum cost. Although she is super smart, she wants to check your smartness as well. Can you tell her the minimum cost required to buy exactly K products if she has already decided to buy product J?
<b>Note:</b> Tono does not buy the same product twice, and Tono will definitely buy product J (J is the <b>index</b> of the item).The first line of the input contains three integers, N, K, and J, denoting the number of products in the market, the number of products Tono needs to buy, and the product that Tono will definitely buy.
The next line contains N singly spaced integers, the cost of the N products C[1], C[2], ..., C[N].
<b>Constraints:</b>
1 <= N <= 200000
1 <= K <= N
1 <= J <= N
1 <= C[i] <= 1000
Output a single integer, the minimum amount Tono needs to pay.Sample Input 1:
5 3 4
1 2 3 4 5
Sample Output 1:
7
Sample Input 2:
5 1 3
2 4 3 1 1
Sample Output 2:
3
<b>Explanation:</b>
Tono needs to buy exactly 3 products, and she will definitely buy the 4th product. Thus, she will buy the 1st, 2nd, and the 4th product. The total cost she pays is 1+2+4=7.
, I have written this Solution Code:
a=input().split()
b=input().split()
for j in [a,b]:
for i in range(0,len(j)):
j[i]=int(j[i])
n,k,j=a[0],a[1],a[2]
c_j=b[j-1]
b.sort()
if b[k-1]<=c_j:
b[k-1]=c_j
sum=0
for i in range(0,k):
sum+=b[i]
print(sum), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Tono loves to do shopping. Today, she went to the market where there are N different types of products. She wants to buy exactly K of them at the minimum cost. Although she is super smart, she wants to check your smartness as well. Can you tell her the minimum cost required to buy exactly K products if she has already decided to buy product J?
<b>Note:</b> Tono does not buy the same product twice, and Tono will definitely buy product J (J is the <b>index</b> of the item).The first line of the input contains three integers, N, K, and J, denoting the number of products in the market, the number of products Tono needs to buy, and the product that Tono will definitely buy.
The next line contains N singly spaced integers, the cost of the N products C[1], C[2], ..., C[N].
<b>Constraints:</b>
1 <= N <= 200000
1 <= K <= N
1 <= J <= N
1 <= C[i] <= 1000
Output a single integer, the minimum amount Tono needs to pay.Sample Input 1:
5 3 4
1 2 3 4 5
Sample Output 1:
7
Sample Input 2:
5 1 3
2 4 3 1 1
Sample Output 2:
3
<b>Explanation:</b>
Tono needs to buy exactly 3 products, and she will definitely buy the 4th product. Thus, she will buy the 1st, 2nd, and the 4th product. The total cost she pays is 1+2+4=7.
, 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(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 pb push_back
#define ll long long
#define ld long double
#define int long long
#define double long double
#define mp make_pair
#define F first
#define S second
typedef pair<int, int> pii;
typedef vector<int> vi;
#define pi 3.141592653589793238
const int MOD = 1e9+7;
const int INF = 1LL<<60;
const int N = 2e5+5;
// 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
void solve(){
int n, k, j; cin>>n>>k>>j;
vector<int> vect;
int ans = 0;
For(i, 1, n+1){
int a; cin>>a;
if(i!=j)
vect.pb(a);
else
ans += a;
}
sort(all(vect));
for(int i=0; i<k-1; i++){
ans += vect[i];
}
cout<<ans;
}
signed main()
{
fast
#ifdef SWAPNIL07
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t=1;
// cin>>t;
while(t--){
solve();
cout<<"\n";
}
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A number (n) is represented in Linked List such that each digit corresponds to a node in linked list. Add 1 to it.
<b>Note:-</b> Linked list representation of a number is from left to right i.e if the number is 123 than in linked list it is represented as 3->2->1<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>addOne()</b> that takes head node of the linked list as parameter.
Constraints:
1 <=length of n<= 1000Return the head of the modified linked list.Input 1:
456
Output 1:
457
Input 2:
999
Output 2:
1000, I have written this Solution Code:
static Node addOne(Node head)
{
Node res = head;
Node temp = null, prev = null;
int carry = 1, sum;
while (head != null) //while both lists exist
{
sum = carry + head.data;
carry = (sum >= 10)? 1 : 0;
sum = sum % 10;
head.data = sum;
temp = head;
head = head.next;
}
if (carry > 0) {
Node x=new Node(carry);
temp.next=x;}
return res;
} , In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given resistance value of N resistors. Find the net resistance of the system when all of these N resistors are connected in parallel.
If there are three resistors A1, A2, A3, when they are connected in parallel, the net resistance will be 1/((1/A1) + (1/A2) + (1/A3))
Since this number can also have a fraction part, you only have to print the floor of the result obtained.
For example, if value of 1/((1/A1) + (1/A2) + (1/A3)) if 7.54567, you only have to print 7.First line contains a single integer N denoting the number of resistors.
Next line contains N space separated integers containing the value of different resistors.
Constraints
1 ≤ N ≤ 10^5
1 ≤ Ai ≤ 10^9Print the integral part or floor of the value obtained from the formula 1/((1/A1) + (1/A2) + ..... + (1/AN)).Input
2
10 30
Output
7
1/((1/10) + (1/30)) = 30/4 = 7.5 and floor of 7.5 is 7, 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());
double arr[] = new double[N];
String str[] = br.readLine().trim().split(" ");
for(int i=0;i<N;i++)
arr[i]=Integer.parseInt(str[i]);
double resistance=0;
int equResistance=0;
for(int i=0;i<N;i++)
arr[i]=Integer.parseInt(str[i]);
for(int i=0;i<N;i++)
{
resistance=resistance+(1/arr[i]);
}
equResistance = (int)Math.floor((1/resistance));
System.out.println(equResistance);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given resistance value of N resistors. Find the net resistance of the system when all of these N resistors are connected in parallel.
If there are three resistors A1, A2, A3, when they are connected in parallel, the net resistance will be 1/((1/A1) + (1/A2) + (1/A3))
Since this number can also have a fraction part, you only have to print the floor of the result obtained.
For example, if value of 1/((1/A1) + (1/A2) + (1/A3)) if 7.54567, you only have to print 7.First line contains a single integer N denoting the number of resistors.
Next line contains N space separated integers containing the value of different resistors.
Constraints
1 ≤ N ≤ 10^5
1 ≤ Ai ≤ 10^9Print the integral part or floor of the value obtained from the formula 1/((1/A1) + (1/A2) + ..... + (1/AN)).Input
2
10 30
Output
7
1/((1/10) + (1/30)) = 30/4 = 7.5 and floor of 7.5 is 7, I have written this Solution Code: r = input("")
r = int(r)
n = input("").split()
resistance=0.0
for i in range(0,r):
resistor = float(n[i])
resistance = resistance + (1/resistor)
print(int(1/resistance)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given resistance value of N resistors. Find the net resistance of the system when all of these N resistors are connected in parallel.
If there are three resistors A1, A2, A3, when they are connected in parallel, the net resistance will be 1/((1/A1) + (1/A2) + (1/A3))
Since this number can also have a fraction part, you only have to print the floor of the result obtained.
For example, if value of 1/((1/A1) + (1/A2) + (1/A3)) if 7.54567, you only have to print 7.First line contains a single integer N denoting the number of resistors.
Next line contains N space separated integers containing the value of different resistors.
Constraints
1 ≤ N ≤ 10^5
1 ≤ Ai ≤ 10^9Print the integral part or floor of the value obtained from the formula 1/((1/A1) + (1/A2) + ..... + (1/AN)).Input
2
10 30
Output
7
1/((1/10) + (1/30)) = 30/4 = 7.5 and floor of 7.5 is 7, 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 n; cin >> n;
double s = 0;
for(int i = 1; i <= n; i++){
double p; cin >> p;
s = s + (1/p);
}
s = 1/s;
cout << floor(s);
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: Given two strings A and B, check if the string A is a sub-string of string B or not.First line of input contains a string A, the second line of the input contains the string B.
Constraints:-
1 < = |A| < = |B| < = 1000
Note:- String will only contain lowercase english letters.Print "Yes" if the string A is the substring of string B, else print "No".Sample Input:-
ewt
newton
Sample Output:-
Yes
Sample Input:-
erf
sdafa
Sample Output:-
No, 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 A=br.readLine();
String B=br.readLine();
int j=0;
boolean flag=false;
for(int i=0;i<B.length();i++)
{
if(A.charAt(j)==B.charAt(i))
{
j+=1;
}
else
j=0;
if(j==A.length())
{
System.out.println("Yes");
flag=true;
break;
}
}
if(!flag)
System.out.println("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, check if the string A is a sub-string of string B or not.First line of input contains a string A, the second line of the input contains the string B.
Constraints:-
1 < = |A| < = |B| < = 1000
Note:- String will only contain lowercase english letters.Print "Yes" if the string A is the substring of string B, else print "No".Sample Input:-
ewt
newton
Sample Output:-
Yes
Sample Input:-
erf
sdafa
Sample Output:-
No, I have written this Solution Code: # Take input from users
MyString1 = input()
MyString2 = input()
if MyString1 in MyString2:
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 two strings A and B, check if the string A is a sub-string of string B or not.First line of input contains a string A, the second line of the input contains the string B.
Constraints:-
1 < = |A| < = |B| < = 1000
Note:- String will only contain lowercase english letters.Print "Yes" if the string A is the substring of string B, else print "No".Sample Input:-
ewt
newton
Sample Output:-
Yes
Sample Input:-
erf
sdafa
Sample Output:-
No, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
// Returns true if s1 is substring of s2
int isSubstring(string s1, string s2)
{
int M = s1.length();
int N = s2.length();
/* A loop to slide pat[] one by one */
for (int i = 0; i <= N - M; i++) {
int j;
/* For current index i, check for
pattern match */
for (j = 0; j < M; j++)
if (s2[i + j] != s1[j])
break;
if (j == M)
return i;
}
return -1;
}
/* Driver program to test above function */
int main()
{
string s1;
string s2 ;
cin>>s1>>s2;
int res = isSubstring(s1, s2);
if (res == -1)
cout << "No";
else
cout <<"Yes";
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: They say friendship is greater than love. Why not play the famous game "FLAMES".
The rules are super simple. Given two strings (all lowercase), remove all the letters that are common to both the strings from both the strings. You cannot erase a character in first string whichever corresponding same character in other string not exist.
For example, in the case
String 1: saumya
String 2: ansh
You can remove only 1 'a' and 1 's' from both the strings.
Remaining strings are:
String 1: umya
String 2: nh
Now all you need to do is find the sum of the remaining strings length % 6.
Output:
If obtained value is 1, output "Friends"
If obtained value is 2, output "Love"
If obtained value is 3, output "Affection"
If obtained value is 4, output "Marriage"
If obtained value is 5, output "Enemy"
If obtained value is 0, output "Siblings"You will be given two strings on different lines.
Constraints
1 <= Length of both the strings <= 100000Output a single string, the result of FLAMES test.Sample Input:-
saumya
ansh
Sample Output:-
Siblings
Explanation:-
after deleting characters :-
str1 = umya
str2 = nh
sum = 4+2
sum%6=0
, 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 str1 = br.readLine();
String str2 = br.readLine();
countCommonCharacters(str1, str2);
}
static void countCommonCharacters(String s1, String s2) {
int[] arr1 = new int[26];
int[] arr2 = new int[26];
for (int i = 0; i < s1.length(); i++)
arr1[s1.codePointAt(i) - 97]++;
for (int i = 0; i < s2.length(); i++)
arr2[s2.codePointAt(i) - 97]++;
int lenToCut = 0;
for (int i = 0; i < 26; i++) {
int leastOccurrence = Math.min(arr1[i], arr2[i]);
lenToCut += (2 * leastOccurrence);
}
System.out.println(findRelation((s1.length() + s2.length() - lenToCut) % 6));
}
static String findRelation(int value) {
switch (value) {
case 1:
return "Friends";
case 2:
return "Love";
case 3:
return "Affection";
case 4:
return "Marriage";
case 5:
return "Enemy";
default:
return "Siblings";
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: They say friendship is greater than love. Why not play the famous game "FLAMES".
The rules are super simple. Given two strings (all lowercase), remove all the letters that are common to both the strings from both the strings. You cannot erase a character in first string whichever corresponding same character in other string not exist.
For example, in the case
String 1: saumya
String 2: ansh
You can remove only 1 'a' and 1 's' from both the strings.
Remaining strings are:
String 1: umya
String 2: nh
Now all you need to do is find the sum of the remaining strings length % 6.
Output:
If obtained value is 1, output "Friends"
If obtained value is 2, output "Love"
If obtained value is 3, output "Affection"
If obtained value is 4, output "Marriage"
If obtained value is 5, output "Enemy"
If obtained value is 0, output "Siblings"You will be given two strings on different lines.
Constraints
1 <= Length of both the strings <= 100000Output a single string, the result of FLAMES test.Sample Input:-
saumya
ansh
Sample Output:-
Siblings
Explanation:-
after deleting characters :-
str1 = umya
str2 = nh
sum = 4+2
sum%6=0
, I have written this Solution Code: name1 = input().strip().lower()
name2 = input().strip().lower()
listA = [0]*26
listB = [0]*26
for i in name1:
listA[ord(i)-ord('a')] = listA[ord(i)-ord('a')] + 1
for i in name2:
listB[ord(i)-ord('a')] = listB[ord(i)-ord('a')] + 1
count = 0
for i in range(0,26):
count = count+abs(listA[i]-listB[i])
res = ["Siblings","Friends","Love","Affection", "Marriage", "Enemy"]
print(res[count%6]), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: They say friendship is greater than love. Why not play the famous game "FLAMES".
The rules are super simple. Given two strings (all lowercase), remove all the letters that are common to both the strings from both the strings. You cannot erase a character in first string whichever corresponding same character in other string not exist.
For example, in the case
String 1: saumya
String 2: ansh
You can remove only 1 'a' and 1 's' from both the strings.
Remaining strings are:
String 1: umya
String 2: nh
Now all you need to do is find the sum of the remaining strings length % 6.
Output:
If obtained value is 1, output "Friends"
If obtained value is 2, output "Love"
If obtained value is 3, output "Affection"
If obtained value is 4, output "Marriage"
If obtained value is 5, output "Enemy"
If obtained value is 0, output "Siblings"You will be given two strings on different lines.
Constraints
1 <= Length of both the strings <= 100000Output a single string, the result of FLAMES test.Sample Input:-
saumya
ansh
Sample Output:-
Siblings
Explanation:-
after deleting characters :-
str1 = umya
str2 = nh
sum = 4+2
sum%6=0
, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define max1 10000001
int main(){
string s1,s2;
cin>>s1>>s2;
string a[6];
a[1]= "Friends";
a[2]= "Love";
a[3]="Affection";
a[4]= "Marriage";
a[5]= "Enemy";
a[0]= "Siblings";
int b[26],c[26];
for(int i=0;i<26;i++){b[i]=0;c[i]=0;}
for(int i=0;i<s1.length();i++){
b[s1[i]-'a']++;
}
for(int i=0;i<s2.length();i++){
c[s2[i]-'a']++;
}
int sum=0;
for(int i=0;i<26;i++){
sum+=abs(b[i]-c[i]);
}
cout<<a[sum%6];
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N people are standing in line numbered 1 to N from left to right. Each person wants to know the height of the person to left of him having height less than him. If there are multiple such people he wants to know the height of the person closest to him.
If there is no such person report -1.The first line of input contains N, the size of the array.
The second line of input contains N space-separated integers.
Constraints
2 ≤ N ≤ 100000
0 ≤ Arr[i] ≤ 1000000000 (Height can be zero wierd people :p )The output should contain N space separated integers, the ith integer should be the height reported to ith person (-1 if no person to the left is found whose height is less).Sample Input 1
5
1 2 3 4 5
Sample Output 1
-1 1 2 3 4
Sample Input 2
2
1 1
Sample Output 2
-1 -1, I have written this Solution Code: import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
final static long MOD = 1000000007;
public static void main(String args[]) {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = fs.nextInt();
int[] a = fs.nextIntArray(n);
Stack<Integer> stck = new Stack<>();
for (int i = 0; i < n; i++) {
while (!stck.isEmpty() && stck.peek() >= a[i]) {
stck.pop();
}
if (stck.isEmpty()) {
out.print("-1 ");
stck.push(a[i]);
} else {
out.print(stck.peek() + " ");
stck.push(a[i]);
}
}
out.flush();
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
} catch (Exception e) {
e.printStackTrace();
}
}
public String next() {
if (st.hasMoreTokens())
return st.nextToken();
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String line = "";
try {
line = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return line;
}
public char nextChar() {
return next().charAt(0);
}
public Integer[] nextIntegerArray(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public char[] nextCharArray() {
return nextLine().toCharArray();
}
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N people are standing in line numbered 1 to N from left to right. Each person wants to know the height of the person to left of him having height less than him. If there are multiple such people he wants to know the height of the person closest to him.
If there is no such person report -1.The first line of input contains N, the size of the array.
The second line of input contains N space-separated integers.
Constraints
2 ≤ N ≤ 100000
0 ≤ Arr[i] ≤ 1000000000 (Height can be zero wierd people :p )The output should contain N space separated integers, the ith integer should be the height reported to ith person (-1 if no person to the left is found whose height is less).Sample Input 1
5
1 2 3 4 5
Sample Output 1
-1 1 2 3 4
Sample Input 2
2
1 1
Sample Output 2
-1 -1, I have written this Solution Code: import sys
n=int(input())
myList = [int(x) for x in sys.stdin.readline().rstrip().split(' ')]
outputList = []
outputList.append(-1);
for i in range(1,len(myList),1):
flag=False
for j in range(i-1,-1,-1):
if myList[j]<myList[i]:
outputList.append(myList[j])
flag=True
break
if flag==False:
outputList.append(-1)
print(*outputList), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N people are standing in line numbered 1 to N from left to right. Each person wants to know the height of the person to left of him having height less than him. If there are multiple such people he wants to know the height of the person closest to him.
If there is no such person report -1.The first line of input contains N, the size of the array.
The second line of input contains N space-separated integers.
Constraints
2 ≤ N ≤ 100000
0 ≤ Arr[i] ≤ 1000000000 (Height can be zero wierd people :p )The output should contain N space separated integers, the ith integer should be the height reported to ith person (-1 if no person to the left is found whose height is less).Sample Input 1
5
1 2 3 4 5
Sample Output 1
-1 1 2 3 4
Sample Input 2
2
1 1
Sample Output 2
-1 -1, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
stack <long long > s;
long long a;
for(int i=0;i<n;i++){
cin>>a;
while(!(s.empty())){
if(s.top()<a){break;}
s.pop();
}
if(s.empty()){cout<<-1<<" ";}
else{cout<<s.top()<<" ";}
s.push(a);
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two positive integers X and Y, check if one integer is obtained by rotating bits of other.
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end.The only line of input contains two integers X and Y
0 <= X, Y <= 2^32 - 1
The numbers are in 32-bit formatPrint "Yes" if its possible otherwise print "No"Sample Input:
8 1
Output:
Yes
Explanation :
Represntation of X = 8 : 0000 0000 0000 0000 0000 0000 0000 1000
Represntation of Y = 1 : 0000 0000 0000 0000 0000 0000 0000 0001
If we rotate X by 3 units right we get Y, hence answer is Yes, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
static boolean isRotation(long x, long y) {
int i = 32;
while (i-- > 0) {
long lastBit = (x & 1);
x >>= 1;
x |= (lastBit << 31);
if(x == y){
return true;
}
}
return false;
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str[] = br.readLine().strip().split(" ");
long x = Long.parseLong(str[0]);
long y = Long.parseLong(str[1]);
if (isRotation(x, y)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two positive integers X and Y, check if one integer is obtained by rotating bits of other.
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end.The only line of input contains two integers X and Y
0 <= X, Y <= 2^32 - 1
The numbers are in 32-bit formatPrint "Yes" if its possible otherwise print "No"Sample Input:
8 1
Output:
Yes
Explanation :
Represntation of X = 8 : 0000 0000 0000 0000 0000 0000 0000 1000
Represntation of Y = 1 : 0000 0000 0000 0000 0000 0000 0000 0001
If we rotate X by 3 units right we get Y, hence answer is Yes, I have written this Solution Code: inp = input().split(" ")
x = int(inp[0])
y = int(inp[1])
counter = 32
while(counter != 0):
z = x & 1
x = x >> 1
x = x + (z << 31)
if(x == y):
print("Yes")
exit()
counter -= 1
print("No"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two positive integers X and Y, check if one integer is obtained by rotating bits of other.
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end.The only line of input contains two integers X and Y
0 <= X, Y <= 2^32 - 1
The numbers are in 32-bit formatPrint "Yes" if its possible otherwise print "No"Sample Input:
8 1
Output:
Yes
Explanation :
Represntation of X = 8 : 0000 0000 0000 0000 0000 0000 0000 1000
Represntation of Y = 1 : 0000 0000 0000 0000 0000 0000 0000 0001
If we rotate X by 3 units right we get Y, hence answer is Yes, I have written this Solution Code: #include "bits/stdc++.h"
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 = 500 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
int a[N][N];
void bin(int x){
for(int i = 0; i < 32; i++){
cout << ((x >> i) & 1);
}
cout << endl;
}
void solve(){
int x = 32;
int a, b;
cin >> a >> b;
while(x--){
int x = (a&1);
a >>= 1;
a += x*(1LL << 31);
/*bin(a); bin(b);
cout << endl;*/
if(a == b){
cout << "Yes";
return;
}
}
cout << "No";
}
void testcases(){
int tt = 1;
//cin >> tt;
while(tt--){
solve();
}
}
signed main() {
IOS;
clock_t start = clock();
testcases();
cerr << (double)(clock() - start)*1000/CLOCKS_PER_SEC << " ms" << 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 S represented as a string, the task is to get the sum of all possible sub-strings of this string.The only line of input contains a single integers S represented as a string.
1 <= len(S) <= 1000000Print the required sum modulo (10^9 + 7)Sample Input 1:
1234
Sample Output 1:
1670
Explanation:
Sum = 1 + 2 + 3 + 4 + 12 + 23 + 34 + 123 + 234 + 1234
= 1670
Sample Input 2:
421
Sample Output 2:
491
Explanation:
Sum = 4 + 2 + 1 + 42 + 21 + 421
= 491, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
static int toDigit(char ch)
{
return (ch - '0');
}
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int n = s.length();
long prev = toDigit(s.charAt(0));
long res = prev;
long current = 0L;
for (int i = 1; i < n; i++){
long numi = toDigit(s.charAt(i));
current = ((i + 1) * numi + 10 * prev)%1000000007;
res =(res+current)%1000000007;
prev = current;
}
System.out.print(res);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer S represented as a string, the task is to get the sum of all possible sub-strings of this string.The only line of input contains a single integers S represented as a string.
1 <= len(S) <= 1000000Print the required sum modulo (10^9 + 7)Sample Input 1:
1234
Sample Output 1:
1670
Explanation:
Sum = 1 + 2 + 3 + 4 + 12 + 23 + 34 + 123 + 234 + 1234
= 1670
Sample Input 2:
421
Sample Output 2:
491
Explanation:
Sum = 4 + 2 + 1 + 42 + 21 + 421
= 491, I have written this Solution Code: s = input().strip()
ln = len(s)
prev = int(s[0])
sm = prev
for i in range(1,ln):
nxt = (i+1)*int(s[i]) + 10 * prev
sm += nxt%1000000007
prev = nxt%1000000007
print(sm%1000000007), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer S represented as a string, the task is to get the sum of all possible sub-strings of this string.The only line of input contains a single integers S represented as a string.
1 <= len(S) <= 1000000Print the required sum modulo (10^9 + 7)Sample Input 1:
1234
Sample Output 1:
1670
Explanation:
Sum = 1 + 2 + 3 + 4 + 12 + 23 + 34 + 123 + 234 + 1234
= 1670
Sample Input 2:
421
Sample Output 2:
491
Explanation:
Sum = 4 + 2 + 1 + 42 + 21 + 421
= 491, I have written this Solution Code: #include "bits/stdc++.h"
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 = 2e6 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
void solve(){
string s;
cin >> s;
int ans = 0, suf = 0;
for(int i = 0; i < (int)s.length(); i++){
suf = (suf*10 + (s[i]-'0')*(i+1)) % mod;
ans = (ans + suf) % mod;
}
cout << ans << endl;
}
void testcases(){
int tt = 1;
//cin >> tt;
while(tt--){
solve();
}
}
signed main() {
IOS;
clock_t start = clock();
testcases();
cerr << (double)(clock() - start)*1000/CLOCKS_PER_SEC << " ms" << endl;
return 0;
} , In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You will be given an array of several arrays that each contain integers and your goal is to write a function that
will sum up all the numbers in all the arrays. For example, if the input is [[3, 2], [1], [4, 12]] then your
program should output 22 because 3 + 2 + 1 + 4 + 12 = 22An array containing arrays which can contain any number of elements.Sum of all the elements in all of the arrays.Sample input:-
[[3, 2], [1], [4, 12]]
Sample output:-
22
Explanation:-
3 + 2 + 1 + 4 + 12 = 22, I have written this Solution Code: function sum_array(arr) {
// store our final answer
var sum = 0;
// loop through entire array
for (var i = 0; i < arr.length; i++) {
// loop through each inner array
for (var j = 0; j < arr[i].length; j++) {
// add this number to the current final sum
sum += arr[i][j];
}
}
console.log(sum);
}, In this Programming Language: JavaScript, 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: You have to complete <code>printName</code> function
<ol>
<li>Takes 2 arguments which are EventEmitter object , event name </li>
<li>Using the <code>EventEmitter</code> object you need to register an eventListener for <code>personEvent</code> event which takes a callback function. </li>
<li>The callback function itself takes an argument (which would be emitted by test runner) which is of type string. Using that argument print to console.
`My name is ${argument}`.
</li>
</ol>Function will take two arguments
1) 1st argument will be an object of EventEmitter class
2) 2nd argument will be the event name (string)
Function returns a registered Event using an object of EventEmitter class (which then is used to print the name)<pre>
<code>
const emitter=EventEmitter object
const personEvent="event"
function printName(emitter,personEvent)//registers event with event Name "event"
emitter.emit("event","Dev")//emits the event and give the output "My name is Dev"
</code>
</pre>
, I have written this Solution Code: function printName(emitter,personEvent) {
emitter.on(personEvent,(arg)=>{
console.log('My name is ',arg);
});
}
, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: <em>Unix time is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, excluding leap seconds. The Unix epoch is 00:00:00 UTC on 1 January 1970</em>
Implement the function <code>msSinceEpoch</code>, which returns milliseconds since the Unix epoch. (Use JS built-in functions)The function takes no argumentThe function returns a numberconsole. log(msSinceEpoch()) // prints 1642595040109, I have written this Solution Code:
function msSinceEpoch() {
// write code here
// return the output , do not use console.log here
return Date.now()
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of N*N dimensions (Mat). Print the matrix rotated by 90 degrees and 180 degrees.The first line contains N.
N lines follow each containing N space-separated integers.
<b>Constraints</b>
2 <= N <= 100
1 <= Mat[i][j] <= 10000Output 2*N+1 lines.
First N lines should contain the Matrix rotated by 90 degrees.
Then print a blank line.
Then N lines should contain the Matrix rotated by 180 degrees.Sample Input 1:
2
3 4
7 6
Sample Output 1:
7 3
6 4
6 7
4 3
Sample Input 2:
2
1 2
3 4
Sample Output 2:
3 1
4 2
4 3
2 1, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define N 1000
// Function to rotate the matrix 90 degree clockwise
void rotate90Clockwise(int a[][N],int n)
{
// Traverse each cycle
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
// Swap elements of each cycle
// in clockwise direction
int temp = a[i][j];
a[i][j] = a[n - 1 - j][i];
a[n - 1 - j][i] = a[n - 1 - i][n - 1 - j];
a[n - 1 - i][n - 1 - j] = a[j][n - 1 - i];
a[j][n - 1 - i] = temp;
}
}
}
// Function for print matrix
void printMatrix(int arr[][N],int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << arr[i][j] << " ";
cout << '\n';
}
}
// Driver code
int main()
{
int n;
cin>>n;
int arr[n][N];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>arr[i][j];
}}
rotate90Clockwise(arr,n);
printMatrix(arr,n);
cout<<endl;
rotate90Clockwise(arr,n);
printMatrix(arr,n);
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of N*N dimensions (Mat). Print the matrix rotated by 90 degrees and 180 degrees.The first line contains N.
N lines follow each containing N space-separated integers.
<b>Constraints</b>
2 <= N <= 100
1 <= Mat[i][j] <= 10000Output 2*N+1 lines.
First N lines should contain the Matrix rotated by 90 degrees.
Then print a blank line.
Then N lines should contain the Matrix rotated by 180 degrees.Sample Input 1:
2
3 4
7 6
Sample Output 1:
7 3
6 4
6 7
4 3
Sample Input 2:
2
1 2
3 4
Sample Output 2:
3 1
4 2
4 3
2 1, I have written this Solution Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[][] = new int[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
a[i][j]= sc.nextInt();
}
}
//rotating by 90 degree
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
int temp = a[i][j];
a[i][j] = a[n - 1 - j][i];
a[n - 1 - j][i] = a[n - 1 - i][n - 1 - j];
a[n - 1 - i][n - 1 - j] = a[j][n - 1 - i];
a[j][n - 1 - i] = temp;
}
}
for(int i =0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
//rotating by 90 degree
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
int temp = a[i][j];
a[i][j] = a[n - 1 - j][i];
a[n - 1 - j][i] = a[n - 1 - i][n - 1 - j];
a[n - 1 - i][n - 1 - j] = a[j][n - 1 - i];
a[j][n - 1 - i] = temp;
}
}
System.out.println();
for(int i =0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of N*N dimensions (Mat). Print the matrix rotated by 90 degrees and 180 degrees.The first line contains N.
N lines follow each containing N space-separated integers.
<b>Constraints</b>
2 <= N <= 100
1 <= Mat[i][j] <= 10000Output 2*N+1 lines.
First N lines should contain the Matrix rotated by 90 degrees.
Then print a blank line.
Then N lines should contain the Matrix rotated by 180 degrees.Sample Input 1:
2
3 4
7 6
Sample Output 1:
7 3
6 4
6 7
4 3
Sample Input 2:
2
1 2
3 4
Sample Output 2:
3 1
4 2
4 3
2 1, I have written this Solution Code: x=int(input())
l1=[]
for i in range(x):
a1=list(map(int,input().split()))
l1.append(a1)
for j in range(x):
for i in range(1,x+1):
print(l1[-i][j], end=" ")
print()
print()
for i in range(1,x+1):
for j in range(1,x+1):
print(l1[-i][-j], end=" ")
print(), In this Programming Language: Python, 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: Numbers are awesome, larger numbers are more awesome!
Given an array A of size N, you need to find the maximum sum that can be obtained from the elements of the array (the selected elements need not be contiguous). You may even decide to take no element to get a sum of 0.The first line of the input contains the size of the array.
The next line contains N (white-space separated) integers denoting the elements of the array.
<b>Constraints:</b>
1 ≤ N ≤ 10<sup>4</sup>
-10<sup>7</sup> ≤ A[i] ≤10<sup>7</sup>For each test case, output one integer representing the maximum value of the sum that can be obtained using the various elements of the array.Input 1:
5
1 2 1 -1 1
output 1:
5
input 2:
5
0 0 -1 0 0
output 2:
0
<b>Explanation 1:</b>
In order to maximize the sum among [ 1 2 1 -1 1], we need to only consider [ 1 2 1 1] and neglect the [-1]., 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 n; cin >> n;
int sum = 0;
for(int i = 1; i <= n; i++){
int p; cin >> p;
if(p > 0)
sum += p;
}
cout << sum;
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Numbers are awesome, larger numbers are more awesome!
Given an array A of size N, you need to find the maximum sum that can be obtained from the elements of the array (the selected elements need not be contiguous). You may even decide to take no element to get a sum of 0.The first line of the input contains the size of the array.
The next line contains N (white-space separated) integers denoting the elements of the array.
<b>Constraints:</b>
1 ≤ N ≤ 10<sup>4</sup>
-10<sup>7</sup> ≤ A[i] ≤10<sup>7</sup>For each test case, output one integer representing the maximum value of the sum that can be obtained using the various elements of the array.Input 1:
5
1 2 1 -1 1
output 1:
5
input 2:
5
0 0 -1 0 0
output 2:
0
<b>Explanation 1:</b>
In order to maximize the sum among [ 1 2 1 -1 1], we need to only consider [ 1 2 1 1] and neglect the [-1]., I have written this Solution Code: n=int(input())
li = list(map(int,input().strip().split()))
sum=0
for i in li:
if i>0:
sum+=i
print(sum), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Numbers are awesome, larger numbers are more awesome!
Given an array A of size N, you need to find the maximum sum that can be obtained from the elements of the array (the selected elements need not be contiguous). You may even decide to take no element to get a sum of 0.The first line of the input contains the size of the array.
The next line contains N (white-space separated) integers denoting the elements of the array.
<b>Constraints:</b>
1 ≤ N ≤ 10<sup>4</sup>
-10<sup>7</sup> ≤ A[i] ≤10<sup>7</sup>For each test case, output one integer representing the maximum value of the sum that can be obtained using the various elements of the array.Input 1:
5
1 2 1 -1 1
output 1:
5
input 2:
5
0 0 -1 0 0
output 2:
0
<b>Explanation 1:</b>
In order to maximize the sum among [ 1 2 1 -1 1], we need to only consider [ 1 2 1 1] and neglect the [-1]., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
int n = Integer.parseInt(br.readLine());
String str[] = br.readLine().split(" ");
long arr[] = new long[n];
long sum=0;
for(int i=0;i<n;i++){
arr[i] = Integer.parseInt(str[i]);
if(arr[i]>0){
sum+=arr[i];
}
}
System.out.print(sum);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.