Contest Solutions
Contest Solutions
1. Number star
Input Format
The first line will contain an integer ‘N’ that is the total number of rows.
Constraints
Output Format
Sample Input 0
5
Sample Output 0
5432*
543*1
54*21
5*321
*4321
Solution:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n;
cin >> n; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(n-j==i+1) cout << "*";
else cout << n-j ;
}
cout << endl;
}
return 0;
}
2. Left rotation
A left rotation operation on an array of size shifts each of the array's elements unit to the
left. Given an integer, , rotate the array that many steps left and return the result.
Function Description
Complete the rotateLeft function in the editor below.
rotateLeft has the following parameters:
• int d: the amount to rotate by
• int arr[n]: the array to rotate
Returns
• int[n]: the rotated array
Input Format
The first line contains two space-separated integers that denote , the number of integers,
and , the number of left rotations to perform.
The second line contains space-separated integers that describe .
Sample Input
54
12345
Sample Output
51234
Solution:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
3. Balanced brackets
----- --------
3 n=3
Solution:
#include <bits/stdc++.h>
switch(s[i]){
case '{':
stack.push_back(s[i]); break;
case '[':
stack.push_back(s[i]); break;
case '(':
stack.push_back(s[i]); break;
case '}':
if(stack.size() == 0){
flag=true;
}
else if('{' != stack.back()){
flag=true;
}
else{
stack.pop_back();
}
break;
case ']':
if(stack.size() == 0){
flag=true;
}
else if('[' != stack.back()){
flag=true;
}
else{
stack.pop_back();
}
break;
case ')':
if(stack.size() == 0){
flag=true;
}
else if('(' != stack.back()){
flag=true;
}
else{
stack.pop_back();
}
break;
}
}
return (flag || (stack.size() != 0)) ? "NO" : "YES";
}
int main() {
int t;
cin >> t; for(int a0 = 0; a0 <
t; a0++){
string s; cin >> s; string
result = isBalanced(s); cout
<< result << endl;
}
return 0;
}
4. Delete duplicate value in likedlist
You are given the pointer to the head node of a sorted linked list, where the data in the
nodes is in ascending order. Delete nodes and return a sorted list with each distinct value
in the original list. The given head pointer may be null indicating that the list is empty.
Example
refers to the first node in the list.
Remove 1 of the data values and return pointing to the revised list.
Function Description
Complete the removeDuplicates function in the editor below.
removeDuplicates has the following parameter:
• SinglyLinkedListNode pointer head: a reference to the head of the list
Returns
• SinglyLinkedListNode pointer: a reference to the head of the revised list
Input Format
The first line contains an integer, the number of test cases.
The first line contains an integer, the number of elements in the linked list.
Each of the next lines contains an integer, the value for each of the elements of the linked
list.
Sample Input
STDIN Function
----- --------
1 t=1
5 n=5
1 data values = 1, 2, 2, 3, 4
2
2
3
4
Sample Output
1234
Solution:
#include <bits/stdc++.h>
using namespace std;
class SinglyLinkedListNode { public:
int data;
SinglyLinkedListNode *next;
SinglyLinkedListNode(int node_data) {
this->data = node_data; this->next =
nullptr;
}
};
SinglyLinkedList() { this-
>head = nullptr; this->tail =
nullptr;
}
if (!this->head) { this-
>head = node;
} else { this->tail->next =
node;
}
this->tail = node;
}
};
if (node) {
fout << sep;
}
}
}
free(temp);
}
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int t;
cin >> t; cin.ignore(numeric_limits<streamsize>::max(),
'\n');
llist->insert_node(llist_item);
}
free_singly_linked_list(llist1);
}
fout.close();
return 0;
}
The height of a binary tree is the number of edges between the tree's root and its furthest
leaf. For example, the following binary tree is of height :
Function Description
Complete the getHeight or height function in the editor. It must return the height of a
binary tree as an integer.
Your function should return a single integer denoting the height of the binary tree.
Solution:
#include <bits/stdc++.h>
class Node {
public: int
data; Node
*left;
Node *right;
Node(int d) {
data = d; left
= NULL;
right = NULL;
}
};
class Solution {
public:
Node* insert(Node* root, int data) {
if(root == NULL) {
return new Node(data);
} else { Node* cur;
if(data <= root->data) {
cur = insert(root->left, data); root-
>left = cur;
} else { cur = insert(root->right,
data); root->right = cur;
}
return root;
}
}
/*The tree node has data, left child and right child
class Node { int data; Node* left;
Node* right;
};
*/
int height(Node* root) {
// Write your code
here.
int leftHeight=-1,rightHeight=-1;
if(root->left){
leftHeight=height(root->left);
}
if(root->right)
rightHeight=height(root->right);
return max(leftHeight,rightHeight)+1;
}
}; //End of Solution
int main() {
Solution myTree;
Node* root = NULL;
int t;
int data;
std::cin >> t;
while(t-- > 0) {
return 0;
}
Contest 2: (arrays)
1: seema and birju
amount of burgers which makes Birju and Seema happy is a number defined by the
following process:
Starting with any positive integer, replace the number by the sum of the squares of its
digits. Repeat the process until the number equals 1 (where it will stay), or it loops
endlessly in a cycle which does not include 1. Those numbers for which this process ends
in 1 are "number of burgers" that makes both of them happy.
Input Format
integer n
Constraints
Output Format
Sample Input 0
19
Sample Output 0
true
Explanation 0
• 1^2 + 9^2 = 82
• 8^2 + 2^2 = 68
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<bits/stdc++.h>
using namespace std;
int summation(int n)
{
int sum =0;
while(n!=0)
{
int rem = n%10;
sum+=rem*rem;
n=n/10;
}
return sum;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */ int
n;
cin>>n;
unordered_set<int> st;
while(n!=1 && st.find(n)==st.end())
{
st.insert(n);
n=summation(n);
}
if(n==1)
cout<<"true"<<endl; else
cout<<"false"<<endl;
return 0;
}
2. Popular number
Given an integer array sorted in non-decreasing order, there is exactly one integer in the
array that occurs more than 25% of the time, return that integer.
Input Format
an array
Constraints
1. 1 <= arr.length <= 104
Output Format
Sample Input 0
1 2 2 6 6 6 6 7 10
Sample Output 0
6
Explanation 0
6 occures 4 times which is more than 25% of the total size of array.
Solution:
#include<bits/stdc++.h>
using namespace std; int
main()
{
vector<int> arr;
int n;
while(cin>>n)
{
arr.push_back(n);
}
n = arr.size(); int
b = n/4; int
count=1; for(int
i=0;i<n;i++)
{
if(arr[i]==arr[i+1])
{
count++;
if(count>b){
cout<<arr[i]<<endl;
break;
}
}
else
{
count=1;
}
}
return 0;
}
3. Anomaly detection
Anomaly detection is the process of analyzing company data to find data points that don't
align with a company's standard data pattern.
Given a 0-indexed integer array nums of length n and an integer target, return the number
of pairs (i, j) where 0 <= i < j < n and nums[i] + nums[j] < target.
Input Format
Constraints
• 1 <= nums.length == n <= 50
Output Format
Sample Input 0
-1 1 2 3 1
2
Sample Output 0
3
Explanation 0
• There are 3 pairs of indices that satisfy the conditions in the statement:
• (0, 1) since 0 < 1 and nums[0] + nums[1] = 0 < target
• Note that (0, 3) is not counted since nums[0] + nums[3] is not strictly less than
the target.
Solution:
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int> arr;
int n; int
target=0;
while(cin>>n
)
{
arr.push_back(n);
target = n;
}
arr.pop_back(); n
= arr.size(); int
count1=0; for(int
i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(arr[i]+arr[j]<target){
count1++;
}
}
}
cout<<count1<<endl;
return 0;
}
OR
class Solution {
public:
int countPairs(vector<int>& nums, int target)
{ int n = nums.size(); sort(nums.begin(),
nums.end());
int count = 0;
int left = 0; int
right = n - 1;
return count;
}
};
4) Finding burger
Birju has an integer array nums that does not contain any zeros, he needs to find a magic
number from that array to get back all the burgers from Seema.
A magic number is the largest positive integer x such that -x also exists in the array.
Input Format
an array
Constraints
• 1 <= nums.length <= 1000
• nums[i] != 0
Output Format
the largest positive integer k such that -k also exists in the array
Sample Input 0
-1 2 -3 3
Sample Output 0
3
Explanation 0
Solution:
int findMaxK ( vector < int > & nums ) { map< int ,
int > mp ;
for ( auto it : nums ) mp [it]++;
4. Finding burgers
//finding burgers
#include<bits/stdc++.h>
using namespace std; int
main()
{
vector<int> arr;
int n;
while(cin>>n)
{
arr.push_back(n);
}
n = arr.size();
unordered_map<int,int> mp;
for(int i=0;i<n;i++)
{
mp[arr[i]]++;
}
int maxi=-1;
for(auto it : mp)
{
if(mp.find(-it.first)!=mp.end())
maxi = max(maxi,abs(it.first));
}
cout<<maxi<<endl;
return 0;
}
5. Highest product
An integer array nums is given. Seema wants to find a subarray that has the largest
product. Return the product.
Input Format
an array
Constraints
1. 1 <= nums.length <= 2 * 104
3. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
Output Format
Sample Input 0
2 3 -2 4
Sample Output 0
6
Explanation 0
Sample Input 1
-2 0 -1
Sample Output 1
0
Output;
#include <bits/stdc++.h>
using namespace std; int
main()
{
vector<int> arr;
int n;
while (cin >> n)
{
arr.push_back(n);
}
n = arr.size(); int
pre = 1, suf = 1; int
ans = INT_MIN;
for (int i = 0; i < n; i++)
{
if (pre ==
0) pre = 1;
if (suf == 0)
suf = 1;
pre = pre * arr[i]; suf = suf *
arr[n - 1 - i]; ans = max(ans,
max(pre, suf));
}
cout<<ans<<endl;
}
Contest 3 (string and matrix)
1. Result observation
There are two classes 6CE1, 6CE2. Given two sorted arrays nums1 and nums2 of size m
and n respectively which contains the low scores of some students in a test result, return
the median of the two sorted arrays to decide overall lowest performance.
Input Format
two arrays
Constraints
nums1.length == m nums2.length == n 0 <= m <= 1000 0 <= n <= 1000 1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
Output Format
Sample Input 0
13
2
Sample Output 0
2.00000
Explanation 0
Solution:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> ans;
int n;
while(cin>>n){
ans.push_back(n);
}
sort(ans.begin(),ans.end());
double median = 0;
if(ans.size()%2==1){
median = (double)ans[ans.size()/2];
}
else{
median = (double)(ans[ans.size()/2]+ans[ans.size()/2-1])/2.0;
}
cout <<fixed<< setprecision(5)<<median;
// cout<<(double)median;
return 0;
}
OR
// Create a single sorted by merging two sorted arrays int n1= nums1 .
size (); int n2= nums2 . size (); int i= 0 ; int j= 0 ; int lastindex=- 1 ;
while (i<n1&&j<n2)
{ if ( nums1 [i]<= nums2 [j]) v [++lastindex]=
nums1 [i++];
else v [++lastindex]= nums2 [j++];
}
} };
2. Disconnection
Given a string s, partition the string into one or more substrings such that the characters
in each substring are unique. That is, no letter appears in a single substring more than
once.
Note that each character should belong to exactly one substring in a partition.
Input Format
a string
Constraints
• 1 <= s.length <= 105
Output Format
Sample Input 0
abacaba
Sample Output 0
4
Explanation 0
• Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
if (s == "") {
cout << 0;
return 0;
}
for (char c : s) { if
(uniqueChars.count(c) == 0) {
uniqueChars.insert(c);
} else {
// Start a new substring when a repeated character is encountered
uniqueChars.clear(); uniqueChars.insert(c); substringCount++;
}
}
// Every unique character starts a new substring, so add 1 for each unique character cout
<< substringCount + uniqueChars.size();
return 0;
}
Given a sorted matrix mat[m][n] and an element ‘x’. Find the position of x in the matrix if
it is present, else print -1.
Matrix is sorted in a way such that all elements in a row are sorted in increasing order and
for row ‘i’, where 1 <= i <= m-1, the first element of row ‘i’ is greater than or equal to the
last element of row ‘i-1’.
Input Format
Constraints
m == matrix.length n == matrix[i].length 1 <= m, n <= 100 -104 <= matrix[i][j], target <=
104
Output Format
Sample Input 0
0 6 7 9 11
20 22 28 29 31
36 38 50 61 63
64 66 100 122 128
31
Sample Output 0
(1,4)
Solution:
#include <iostream>
#include <vector>
#include <sstream>
int main() {
std::vector<std::vector<int>> ar;
Jake has two lane road in which each lane has different valued coins.
you can imagine it as a two sorted arrays of integers which represent the values of coins,
find a sequence of path involving elements of both arrays/lanes whose sum is maximum
so that Jake can grab maximum amount of coins.
We can start from either array/lane , but we can switch between arrays/lanes only
through its common elements.
Input Format
2 arrays
Constraints
Output Format
Sample Input 0
3 6 7 8 10 12 15 18 100
1 2 3 5 7 9 10 11 15 16 18 25 50
Sample Output 0
199
Explanation 0
The path is: 1 —> 2 —> 3 —> 6 —> 7 —> 9 —> 10 —> 12 —> 15 —> 16 —> 18 —> 100
Solution:
#include <iostream>
#include <vector>
#include <sstream>
// Utility function to find the maximum of two
integers int max(int x, int y) { return (x > y) ? x : y;
}
// Function to find the maximum sum path in two given arrays. // The code
is similar to the merge routine of the merge sort algorithm int
subwaySurf(const std::vector<int>& arr1, const std::vector<int>& arr2) { int
sum = 0; int sum_x = 0, sum_y = 0;
// `i` and `j` denotes the current index of `arr1` and `arr2`, respectively int
i = 0, j = 0;
// if the current element of `arr2` is less than the current element of `arr1` if
(arr2[j] < arr1[i]) {
sum_y += arr2[j];
j++;
}
// if the current element of `arr1` is less than the current element of `arr2` else
if (arr1[i] < arr2[j]) {
sum_x += arr1[i];
i++;
}
int main() {
std::string line;
1234 2 3 4 5 3 4 5 6
12 1 2 5 -> 1 2 3 6 -> 2 3 4 7
11 4 3 6 12 1 4 7 1 2 1 8
10 9 8 7 11 10 9 8 12 11 10 9
Function Description
Complete the matrixRotation function in the editor below.
----- --------
1234 matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
5678
9 10 11 12
13 14 15 16
int main() {
int W,H,R;
cin>>H>>W>>R; int
ncycles=min(W,H)/2;
int m[W*H]; int
cycles[150][1196];
int i,x,y; int cycle,cyclelen;
for(i=0;i<W*H;i++)cin>>m[i];
for(cycle=0;cycle<ncycles;cycle++){
i=0;
x=y=cycle; for(;y<H-cycle-1;y++)cycles[cycle][i++]=m[W*y+x];
for(;x<W-cycle-1;x++)cycles[cycle][i++]=m[W*y+x];
for(;y>cycle;y--)cycles[cycle][i++]=m[W*y+x]; for(;x>cycle;x--
)cycles[cycle][i++]=m[W*y+x];
}
for(cycle=0;cycle<ncycles;cycle++){
cyclelen=2*(W-2*cycle)+2*(H-2*cycle)-4; i=-
R%cyclelen+cyclelen; x=y=cycle; for(;y<H-cycle-
1;y++)m[W*y+x]=cycles[cycle][i++%cyclelen]; for(;x<W-
cycle-1;x++)m[W*y+x]=cycles[cycle][i++%cyclelen];
for(;y>cycle;y--)m[W*y+x]=cycles[cycle][i++%cyclelen];
for(;x>cycle;x--)m[W*y+x]=cycles[cycle][i++%cyclelen];
}
for(y=0;y<H;y++){
for(x=0;x<W;x++){
if(x)cout<<' ';
cout<<m[W*y+x];
}
cout<<endl;
}
return 0;
}
Or
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
// Main algorithm: in order to rotate the whole matrix, we'll just rotate one ring at a time
// We can do this in-place to achieve O(1) additional space complexity int
main() {
int M, N, R;
cin>>M>>N>>R;
int **matrix = new int*[M];
for(int i = 0; i < M; i++) {
matrix[i] = new int[N]; for(int j
= 0; j < N; j++) {
cin>>matrix[i][j];
}
}
In one move, a player can remove any one card from the remaining cards on the desk.
Find the minimum number of moves required so that all the cards remaining on the desk
have the same number written on them.
Input Format
The first line contains a single integer T — the number of test cases. Then the test cases
follow. The first line of each test case contains an integer N — the number of cards on the
table. The second line of each test case contains N space-separated integers
1,2,…,A1,A2,…,AN where Ai is the number written on the i th card.
Constraints
• 1≤T≤100
• 1≤N≤100
• 1≤Ai≤10
Output Format
For each test case, output the minimum number of moves required so that all the UNO
cards remaining on the desk have the same number written on them.
Sample Input 0
3
5
11223
4
8888
6
5 6 7 8 9 10
Sample Output 0
3
0
5
Explanation 0
• Test case 1: The minimum number of moves required such that all remaining
cards have same values is 3: Move 1: Remove a card with number 1. Remaining
cards are [1, 2, 2, 3]. Move 2: Remove a card with number 1. Remaining cards
are [2, 2, 3]. Move 3: Remove a card with number 3. Remaining cards are [2,2].
• Test case 2: All cards have the same number initially. Thus, no moves are
required.
• Test case 3: The minimum number of moves required such that all remaining
cards have same values is 5: Move 1: Remove a card with number 5. Remaining
cards are [6, 7, 8, 9, 10]. Move 2: Remove a card with number 6. Remaining
cards are [7, 8, 9, 10]. Move 3: Remove a card with number 7. Remaining cards
are [8, 9, 10]. Move 4: Remove a card with number 8. Remaining cards are [9,
10]. Move 5: Remove a card with number 9. Remaining cards are [10].
Solution;
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;// n-max repeat = ans
// we have to find out max repeat//
int a[n],sum=0;
for(int j=1;j<=n;j++)
{
cin>>a[j];
}
for(int i=1;i<=10;i++)
{
int count=0; for(int
j=1;j<=n;j++) {
if(a[j]==i) {
count++;
}
}
if(sum<count)
{
sum=count;
}
}
cout<<n-sum<<endl;
return 0;
}
2. End sorting
• user considers a permutation P of {1,2,3,..., N} End Sorted if and only if P1 = 1
and Pn = N.
• In one operation Chef can choose any index i (1 ≤ i ≤ N - 1) and swap Pi and
Pi+1. Determine the minimum number of operations required by you to make
the permutation P End Sorted.
Input Format
• • The first line of input will contain a single integer T, denoting the number of
test cases.
• • The first line of each test case contains a single integer N. denoting the length
of the permutation P.
• • The second line contains N space-separated integers P1, P2, P3,..., PN. denoting
the permutation P.
Constraints
• 1 <= T <= 1000
• P is a permutation of {1,2,3,... N}
• The sum of N over all test cases does not exceed 3*10^5.
Output Format
For each test case, output minimum number of operations required by you to make the
permutation P End Sorted.
Sample Input 0
4
4
1324
3
321
2
21
3
213
Sample Output 0
0
3
1
1
Explanation 0
• Test case 1: P is already End Sorted.
• Test case 2: P can be made End Sorted using 3 operations as follows: [3, 2, 1] →
[2,3,1]→ [2, 1, 3]→ [1, 2, 3]. It can be shown that achieving this in fewer than 3
moves is impossible.
• Test case 3: P can be made End Sorted using one operation, by swapping 1 and
2.
• Test case 4: P can be made End Sorted using one operation, by swapping 1 and
2.
Solution:
#include <iostream>
using namespace std;
3. SGP
Ashwin sir is announcing a Software group project under his guidance at the orrientation
program and N students are invited to it. Everyone has arrived and they are eager to make
a group and select their appropriate domain of project.
Input Format
• • The first line of input will contain a single integer T. denoting the number of
test cases.
• • The first line of each test case contains an integer N- the number of people at
the party.
• • The next line contains the array P - where Pi denotes the preferred group size
for i th person.
Constraints
• 1 ≤ T ≤ 1000
Output Format
For each test case, output YES, if sir can assign every person to a group such that everyone
remains happy. Otherwise output NO.
Sample Input 0
4
5
23233
5
55555
5
32232
4
4443
Sample Output 0
YES
YES
NO
NO
Explanation 0
• Test case 1: Person 1 and 3 can make a group (As both want to be in a group of
2). Person 2, 4 and 5 can make a group (As they all want to be in a group of 3).
So, there is a possible arrangement that sir can make so that all of them are
happy.
• Test case 2: All of the 5 people can make a group (As all want to be in a group of
5). So, there is a possible arrangement that sir can make so that all of them are
happy.
• Test case 3: It can be shown that there is no possible arrangement that sir can
make so that all of them are happy.
• Test case 4: It can be shown that there is no possible arrangement that sir can
make so that all of them are happy.
Solution:
#include <bits/stdc++.h>
using namespace std;
vector<int>ans(people+1,0);
for(int i=0;i<v.size();i++){
ans[v[i]]++;
}
• For example, 0, 1, 01, 10, 101, 010, 1010 are alternating strings while 11, 001,
1110 are not.
• You are given a binary string S of length N. You would like to rearrange the
characters of S such that the length of the longest alternating substring of S is
maximum. Find this maximum value.
• A binary string is a string that consists of characters 0 and 1. A string a is a
substring of a string b if a can be obtained from b by deletion of several
(possibly, zero or all) characters from the beginning and several (possibly, zero
or all) characters from the end.
Input Format
• • The first line of input contains an integer T, denoting the number of test cases.
The T test cases then follow:
• • The second line of each test case contains the binary string S.
Constraints
• • 1 <= T <= 10^4
• • 1 ≤ N ≤ 10^5
Output Format
For each test case, output the maximum possible length of the longest alternating
substring of S after rearrangement.
Sample Input 0
4
3
110
4
1010
4
0000
7
1101101
Sample Output 0
3
4
1
5
Explanation 0
• Test case 1: Swapping the second and third characters makes S = 101. Hence the
length of the longest alternating substring is 3 (choosing the entire string as a
substring).
• Test case 3: The length of the longest alternating substring is 1 for any
rearrangement of S = 0000.
Solution:
#include <bits/stdc++.h> #include
<iostream>
using namespace std;
int main() {
// your code goes here
short test; cin>>test;
while(test--)
{
int n; cin>>n;
char str[n]; int tzero=0;
int tone=0; for(int
i=0;i<n;i++){ cin>>str[i];
if(str[i]=='0')
tzero++; else
tone++;
}
int min_num = min(tzero , tone);
int max_num = max(tzero,tone);
if(min_num==max_num){
cout<<max_num+ min_num<<endl;
}
else if( min_num + 1<=max_num)
{
cout<<2*min_num + 1<<endl;
}
else{
cout<<1<<endl;
}
return 0;
}
5. Learning HTML
one of your junior recently developed an interest in Web Development and started learning HTML.
Now he wants to create his own HTML Code Editor. As a subproblem, he wants to check if a typed
HTML closing tag has correct syntax or not.
Help him by printing "Success" if the tag is fine. If not, print "Error".
Input Format
• The first line contains an integer T, the number of test cases. Then T test cases
follow.
• Each test case is a single line of input, a string describing the tag.
Constraints
• • 1<=T<=1000
• • 1 ≤ length(Tag) ≤ 1000
• • The characters of the string belong to the ASCII range [33,126] (note that this
excludes space.)
Output Format
For each test case, output in a single line, "Success" if it is a valid closing tag and "Error"
otherwise (without quotes).
You may print each character of the string in uppercase or lowercase (for example, the
strings "SuccEss", "success", "Success", "SUCCESS" etc. will all be treated as identical).
Sample Input 0
5
</h1>
Clearly_Invalid
</singlabharat>
</5>
<//aA>
Sample Output 0
Success
Error
Success
Success
Error
Explanation 0
• Test Cases 1, 3, 4: The tags follow all mentioned constraints.
• Test Case 2: The tag doesn't contain opening and closing symbols and also
includes characters other than lower-case alpha-numeric characters in its body.
• Test Case 5: The tag also includes an upper-case alpha-numeric character "A"
and a non alpha-numeric character "/" in its body.
Solution:
#include <bits/stdc++.h>
using namespace std; #define
ll long long int
int main()
{
ll t,n,i,j,k;
cin >> t; while(t-
-)
{
string s; cin
>> s; if(s.length()<=3)
{
cout << "Error\n";
continue;
}
if((s[0]!='<')||(s[s.length()-1]!='>')||(s[1]!='/'))
{
cout << "Error\n";
continue;
}
for(i=2;i<s.length()-1;i++)
{
if((s[i]>='0' && s[i]<='9')||(s[i]>='a' && s[i]<='z'))
continue;
else
break;
}
if(i==s.length()-1)
cout << "Success\n";
else
cout << "Error\n";
}
return 0;
}
Contest: 19/1/24 (revision 2)
1. Find culprits
Kumandra city's residence knows about two languages spoken in their locality. The first
language contains lowercase English letters between 'a' and 'm' inclusive and the second
language contains only uppercase English letters between 'N' and 'Z' inclusive.
however there are a group of culprits from another country that are not proficient in any
of those languages. You as a sherif captured a group of suspicious people and you need to
identify the true residence of Kumandra.
• the sentence contains only the characters from the two given languages.
each word of residence's sentence contains only characters from one of the languages, but
different words may come from different languages.
Due to culprits' limited vocabulary, they sometimes mixes the languages when forming a
sentence.
you as a sherif need to determine the residence identity by testing their written
sentences.
You are given a sentence as a sequence of K words S1, S2,..., SK. Determine whether it
could be a sentence formed by the residence of Kumandra or not, i.e. if it contains only the
characters from the two given languages and each word contains only characters from a
single language.
Input Format
• • The first line of the input contains a single integer T denoting the number of
test cases. The description of T test cases follows.
• • The first and only line of each test case contains an integer K followed by a
space and K space-separated strings S1, S2,..., SK.
Constraints
• 1 <= T <= 10^5
• 1 <= K <= 10
• the sum of lengths of all the strings on the input does not exceed 105
Output Format
For each test case, print a single line containing the string "YES" if the given sentence can
be formed by residence of Kumandra or "NO" if it is formed by culprits.
Sample Input 0
3
1 aN
2 ab NO
3AND
Sample Output 0
NO
YES
NO
Solution:
#include<bits/stdc++.h> using
namespace std; #define ll long
long
#define int long long
#define fast ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
#define endl "\n"
#define maxim(l) *max_element(l.begin(),l.end())
#define minim(l) *min_element(l.begin(),l.end())
#define sum(l) accumulate(l.begin(),l.end(),0ll)
#define ssort(l) sort(l.begin(),l.end())
#define revs(l) sort(l.rbegin(),l.rend())
#define rev(l) reverse(l.begin(),l.end())
void minmax(int &a,int &b){int temp=min(a,b);b=max(a,b);a=temp;}
/***********************************************************************
***********************************************/ signed
main(){ int t;cin>>t; while(t--){ int n;cin>>n;
int lang1,lang2;bool flag=false;
// set<char>myset1={'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'};
// set<char>myset2={'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
for(int i=0;i<n;i++){ string s;cin>>s; lang1=0;lang2=0;
for(int i:s){
if(i>=91 and i<=109){
lang1++;
}
else if(i>=78 and i<=90){
lang2++;
}
else{flag=true;}
}
}if(flag){cout<<"NO"<<endl;continue;}
if((lang1==0 or lang2==0)and(lang1 or lang2)){
cout<<"YES"<<endl;
}
else{cout<<"NO\n";}
}
}
2. Watch
It's possible for all the digits displayed on a digital clock in the hours:minutes format to
be identical. The time 3:33 is an example of such a situation. Other examples are 2:2 and
1:11. Note that the digits of 33:33 are identical, but it is not a valid time on a usual digital
clock.
The above example was for a usual 24-hour format digital clock. Let's consider a more
general clock, where an hour lasts M minutes and a day lasts H hours (therefore, the clock
can show any number of hours between 0 and H-1, inclusive, and any number of minutes
between 0 and M-1, inclusive). Both the hours and the minutes are shown without leading
zeroes in decimal notation and their separator (e.g., ':') doesn't matter.
Can you tell how many minutes during a day will the digital clock have identical digits
displayed on it?
Input Format
• The first line of the input contains an integer T - the number of test cases.
• Each of the next T lines contains two space-separated integers H and M for one
test case.
Constraints
• 1 ≤ T ≤ 50
• 1 ≤ H, M ≤ 100
Output Format
For each test case, output a single line corresponding to the answer of the problem.
Sample Input 0
6
24 60
34 50
10 11
10 12
11 11
11
Sample Output 0
19
20
10
11
10
1
Explanation 0
• Example case 1. A clock shows two identical digits at times 0:0, 1:1, .., 9:9, three
identical digits at times 11:1, 22:2, 1:11, 2:22, 3:33, 4:44, 5:55, and four identical
digits at times 11:11 and 22:22. So, there are 19 minutes during which the time
displayed by the clock will have identical digits.
• Example case 2. Compared to the previous case, the clock doesn't show 5:55,
but can show 33:3 and 33:33.
• Example case 6. In this example, our day consists of one hour and one hour
consists of one minute. Hence, the entire day is just 1 minute - the only time the
digital clock will display is 0:0 during the entire day, (i.e. the entire hour, i.e.
entire minute). And 0:0 has all digits identical, so the answer is 1.
Solution:
#include<bits/stdc++.h>
# define ll long long int
#define vec vector
#define um unordered_map
#define us unordered_set
#define ms multiset
#define mm multimap
#define pb push_back
#define st string
#define ub upper_bound
#define lb lower_bound using
namespace std;
const int m=1e9+7;
int main(){
int t; cin>>t; while(t--){ int a,b;
cin>>a>>b; vec<int>sd={0,1,2,3,4,5,6,7,8,9};
vec<int>df={00,11,22,33,44,55,66,77,88,99};
int count=0;
for(auto i:sd){
if(i<a&&i<b) count++;
}
for(int k=1;k<df.size();k++){
if(df[k]<a&&df[k]<b){
count++;
}
}
for(int
l=1,j=1;l<sd.size(),j<df.size();l++,j++){
if(sd[l]<a&&df[j]<b) count++;
if(sd[l]<b&&df[j]<a) count++;
}
cout<<count<<endl;
}
return 0 ;
}
3. Easy physics
• There are N subatomic particles lined up in a row. There are two types: protons
and electrons. Protons have a positive charge and are represented by 1, while
electrons have a negative charge and are represented by 0.
Input Format
• • The first line contains an integer T, the number of test cases. Then the test
cases follow.
• • The second line contains a string S of length N, where S; represents the initial
charge on i-th particle.
• • The third line contains K integers Q1, Q2,..., QK, the positions of the changed
particles.
Constraints
• • 1<=T<=5
• • 1 <= N, K ≤ 10^5
• • 1 <= Qi <= N
Output Format
For each test case, output K lines, where the i-th line contains the answer after the
updates Q1,..., Qi have been made.
Sample Input 0
1
33
010
213
Sample Output 0
4
3
2
Explanation 0
• Update 1: After reversing the parity of particle 2, the new configuration is 000.
Since all the particles have a similar charge, each is separated from the previous
by a distance of 2 units. So the location of particle 3 is 2 + 2 = 4 units from the
first particle.
• Update 2: After reversing the parity of particle 1, the new configuration is 100.
Here, the charges of particles 1 and 2 differ, so they are separated by 1 unit. The
charges of particles 2 and 3 agree, so they are separated by 2 units. So, the
location of particle 3 is 1 + 2 = 3 units from the first particle.
• Update 3: After reversing the charge of particle 3, the new configuration is 101.
Here, particles 1 and 2 are separated by 1 unit and particles 2 and 3 are
separated by 1 unit. So the location of particle 3 is 1 + 1 = 2 units from the first
particle.
Solution:
#include<bits/stdc++.h>
#define cin(arr,n) for(int
i=0;i<n;i++)cin>>arr[i] typedef long long ll; using
namespace std;
int main() {
int t; cin>>t;
while(t--)
{
int n,k; cin>>n>>k;
string s; cin>>s; int
arr[k]; cin(arr,k);
if(n==1)
{
for(int i=0;i<k;i++)
cout<<0<<endl; continue;
}
ll distance=0;
for(int i=1;i<n;i++)
{ if(s[i]==s[i-
1])
distance+=2;
else
distance+=1;
}
for(int i=0;i<k;i++)
{
if(arr[i]==1 )
{
if(s[0]==s[1])
distance--; else
distance++;
}
else if(arr[i]==n)
{
if(s[n-1]==s[n-2])
distance--; else
distance++;
}
else
{
int temp=0; if(s[arr[i]-
1]==s[arr[i]-2]) temp=temp+2;
if(s[arr[i]-1]!=s[arr[i]-2])
temp+=1; if(s[arr[i]-1]!=s[arr[i]])
temp+=1; if(s[arr[i]-
1]==s[arr[i]])
{
temp++; temp++;
}
if(temp==4) distance=distance-2;
if(temp==2)distance=distance+2;
}
if(s[arr[i]-1]=='0')
s[arr[i]-1]='1'; else
s[arr[i]-1]='0';
cout<<distance<<endl;
}
}
return 0;
}
4.Kindergarten
adventure
Meera teaches a class of students, and every day in her classroom is an adventure. Today
is drawing day!
The students are sitting around a round table, and they are numbered from to in
the clockwise direction. This means that the students are numbered , and
students and are sitting next to each other.
After letting the students draw for a certain period of time, Meera starts collecting their
work to ensure she has time to review all the drawings before the end of the day.
However, some of her students aren't finished drawing! Each student needs extra
minutes to complete their drawing.
Meera collects the drawings sequentially in the clockwise direction, starting with student
ID , and it takes her exactly minute to review each drawing. This means that
student gets extra minutes to complete their drawing, student gets extra minute,
student gets extra minutes, and so on. Note that Meera will still spend minute for each
student even if the drawing isn't ready.
Given the values of , help Meera choose the best possible to start collecting drawings
from, such that the number of students able to complete their drawings is maximal. Then
print on a new line. If there are multiple such IDs, select the smallest one.
Input Format
The first line contains a single positive integer, , denoting the number of students in the
class.
The second line contains space-separated integers describing the respective amounts of
time that each student needs to finish their drawings (i.e., ).
Output Format
Print an integer denoting the ID number, , where Meera should start collecting the
drawings such that a maximal number of students can complete their drawings. If there
are multiple such IDs, select the smallest one.
Solution:
#include <bits/stdc++.h>
using namespace std;
int start = 0;
• Find whether there exists a pair of indices (i, j) (1 ≤ i < j ≤ N) such that abs(Ai -
Aj) = B.
Input Format
• • The first line of input will contain a single integer T, denoting the number of
test cases.
• • The first line of each test case contains two space-separated integers N and B.
Constraints
• • 1 <= T <= 100
• • 1 ≤ N ≤ 10^5
Output Format
For each test case, output on a new line 1 if there exists a pair of indices (i, j) (1 <= i < j <=
N) such that abs(Ai - Aj) = B, or 0 otherwise.
Sample Input 0
3
6 78
5 10 3 2 50 80
2 30
-10 20
45
1234
Sample Output 0
1
1
0
Explanation 0
• Test case 1: Given A as [5, 10, 3, 2, 50, 80]. Elements with difference 78 are A6 =
80 and A4 = 2.
• Test case 2: Given A as [-10, 20]. Elements with difference 30 are A₂ = 20 and A₁
= -10.
• Test case 3: Given A as [1, 2, 3, 4]. No such pairs exists where difference of
elements is 5.
Solution:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
int T; std::cin
>> T;
std::sort(A.begin(), A.end());
int i = 0, j = 0, match = 0;
while (i < N && j < N) {
int D = A[j] - A[i]; if (D
== B) { match = 1;
break;
} else if (D > B) {
i++; } else {
j++;
}
}
std::cout << match << std::endl;
}
return 0;
}
2. Bit manipulation
problem
• For example, in the 8-bit binary number 11010101, the least significant bit is the
rightmost bit, which is 1 in this case.
-
- Most Significant Bit
• The most significant bit (MSB) is the leftmost bit in a binary representation of a
number. In binary notation, each bit represents a power of 2, with the leftmost bit
typically representing the largest power of 2 in the number. The term "most significant"
indicates that this bit contributes the most to the overall value of the number.
• For example, in the 8-bit binary number 11010101, the most significant bit is the
leftmost bit, which is 1 in this case.
Input Format
Constraints
0 <= N <= 100
Output Format
Sample Input 0
6
Sample Output 0
3
Sample Input 1
7
Sample Output 1
2
Solution:
#include <iostream> using
namespace std;
n1 /=2;
pos++;
pos--;
3. Pizza party
#include <bits/stdc++.h>
using namespace std;
if(b%a == 0){
return a;
}
return gcd(b%a,a);
int main() {
cin >> t;
while(t--) {
return 0;
}
4. Array
manipulation
• Happy has a permutation P of length 2*N. He can perform the following
operation on P:
• Happy would call the permutation P good, if the maximum element of the first
half of P is less than the minimum element of the second half of P.
• Find the minimum number of operations Happy needs to apply to make P good.
Input Format
• • The first line contains a single integer T - the number of test cases. Then the
test cases follow.
• • The first line of each test case contains an integer N - half the size of the
permutation P.
• • The second line of each test case contains 2. N space-separated integers P1,
P2,..., P(2-N). denoting the permutation P.
Constraints
• • 1 <= T <= 10^5
Output Format
For each test case, output the minimum number of operations required to make P good.
Sample Input 0
3
2
3214
3
123456
3
654321
Sample Output 0
2
0
9
Explanation 0
• Test case 1: We can perform the following operations:
• Apply operation at i=1: [3, 2, 1, 4]→[2,3,1,4]
Solution:
#include <iostream>
using namespace std;
int main() {
long long int t,i,n,k;
cin>>t;
for(i=0;i<t;i++){
cin>>n;
long long int a=2*n;
long long int arr[a];
long long int j=0;
long long int count=0;
for(k=0;k<a;k++){
cin>>arr[k];
if(arr[k]>n){
count+=n-k+j;
j++;
}
}
cout<<count<<endl;
return 0;
Given pointers to the head nodes of linked lists that merge together at some point, find
the node where the two lists merge. The merge point is where both lists point to the same
node, i.e. they reference the same memory location. It is guaranteed that the two head
nodes will be different, and neither will be NULL. If the lists share a common node, return
that node's value.
Note: After the merge point, both lists will share the same node pointers.
Example
In the diagram below, the two lists converge at Node x:
[List #1] a--->b--->c
\
x--->y--->z--->NULL
/
[List #2] p--->q
Function Description
Complete the findMergeNode function in the editor below.
findMergeNode has the following parameters:
• SinglyLinkedListNode pointer head1: a reference to the head of the first list
• SinglyLinkedListNode pointer head2: a reference to the head of the second list
Returns
• int: the value of the node where the lists merge
Input Format
Do not read any input from stdin/console.
The first line contains an integer , the number of test cases.
Each of the test cases is in the following format:
The first line contains an integer, , the node number where the merge will occur.
The next line contains an integer, that is the number of nodes in the first list.
Each of the following lines contains a value for a node. The next line contains an
integer, that is the number of nodes in the second list.
Each of the following lines contains a value for a node.
Sample Input
The diagrams below are graphical representations of the lists that input nodes and are
connected to.
Test Case 0
1
\
2--->3--->NULL
/
1
Test Case 1
1--->2
\
3--->Null
/
1
Sample Output
2
3
Solution:
int findMergeNode(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2)
{
SinglyLinkedListNode* current1 = head1;
SinglyLinkedListNode* current2 = head2;
You’re given the pointer to the head nodes of two linked lists. Compare the data in the
nodes of the linked lists to check if they are equal. If all data attributes are equal and the
lists are the same length, return 1. Otherwise, return 0.
The two lists have equal data attributes for the first nodes. is longer, though, so the lists
are not equal. Return 0.
Function Description
Complete the compare_lists function in the editor below.
compare_lists has the following parameters:
• SinglyLinkedListNode llist1: a reference to the head of a list
• SinglyLinkedListNode llist2: a reference to the head of a list
Returns
• int: return 1 if the lists are equal, or 0 otherwise
Input Format
The first line contains an integer , the number of test cases.
Each of the test cases has the following format:
The first line contains an integer , the number of nodes in the first linked list.
Each of the next lines contains an integer, each a value for a data attribute.
The next line contains an integer , the number of nodes in the second linked list.
Each of the next lines contains an integer, each a value for a data attribute.
Output Format
Compare the two linked lists and return 1 if the lists are equal. Otherwise, return 0. Do
NOT print anything to stdout/console.
For each test case, in a new line, print if the two lists are equal, else print .
Sample Input
2
2
1
2
1
1
2
1
2
2
1
2
Sample Output
0
1
Explanation
There are test cases, each with a pair of linked lists.
• In the first case, linked lists are: 1 -> 2 -> NULL and 1 -> NULL
• In the second case, linked lists are: 1 -> 2 -> NULL and 1 -> 2 -> NULL
Solution:
// Complete the compare_lists function below.
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode* next;
* };
*
*/
bool compare_lists(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2)
{
while(head1!=NULL && head2!=NULL){
if(head1->data != head2->data){
return 0;
}
head1 = head1->next;
head2 = head2->next;
}
return head1==NULL && head2==NULL ? 1 : 0;
A position of 0 indicates head, a position of 1 indicates one node away from the head and
so on. The head pointer given may be null meaning that the initial list is empty.
Solution:
/*
* Complete the 'insertNodeAtPosition' function below.
*
* The function is expected to return an INTEGER_SINGLY_LINKED_LIST.
* The function accepts following parameters:
* 1. INTEGER_SINGLY_LINKED_LIST llist
* 2. INTEGER data
* 3. INTEGER position
*/
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode* next;
* };
*
*/
return llist;
}
Function Description
Complete the mergeLists function in the editor below.
mergeLists has the following parameters:
• SinglyLinkedListNode pointer headA: a reference to the head of a list
• SinglyLinkedListNode pointer headB: a reference to the head of a list
Returns
• SinglyLinkedListNode pointer: a reference to the head of the merged list
Input Format
The first line contains an integer , the number of test cases.
The first line contains an integer , the length of the first linked list.
The next lines contain an integer each, the elements of the linked list.
The next line contains an integer , the length of the second linked list.
The next lines contain an integer each, the elements of the second linked list.
Sample Input
1
3
1
2
3
2
3
4
Sample Output
12334
Solution:
SinglyLinkedListNode* mergeLists(SinglyLinkedListNode* head1,
SinglyLinkedListNode* head2) {
SinglyLinkedListNode* mergedHead = NULL;
SinglyLinkedListNode* mergedTail = NULL;
return mergedHead;
}
5. naive pedestrian
There's a zebra crossing appearing in the middle of nowhere with N blocks in it. The
colors of the zebra crossing is represented by a binary string S, where Si is 1 if the i th
block from the left is white, and 0 if the block is black.
A pedestrian really wants to play with the zebra crossing. Although the given zebra
crossing might not have alternate black and white blocks, pedestrian wants to follow the
alternating white-black color pattern while crossing it.
Initially, pedestrian stands at block 1. pedestrian has to jump exactly K times, and in each
jump he has to move forward and jump to a different color than that previously occupied
by pedestrian. More formally, suppose that pedestrian is currently at block i and wants to
jump to block j then following conditions should hold:
• i<j
• Si != Sj
Output the farthest block pedestrian can reach with exactly K jumps. If pedestrian cannot
jump exactly K times, output -1.
Input Format
The first line contains an integer T denoting the number of test cases. The T test cases
then follow.
The first line of each test case contains two integers N and K.
The second line of each test case consists of a binary string of length N denoting the color
of blocks of the zebra crossing.
Constraints
• • 1 <= T <= 10^5
• • 2 ≤ N ≤ 10^3
• • 1 <= K <= N
Output Format
For each test case, output the farthest block padestrian can reach with exactly K jumps, or
-1 in case padestrian cannot jump exactly K times.
Sample Input 0
3
62
100101
51
10111
61
000000
Sample Output 0
6
2
-1
Explanation 0
For the first test case, he can jump in the following order: 1→5→6.
For the second test case, he can jump in the following order: 1→2.
Solution:
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
void solve() {
ll n, k;
cin >> n >> k;
string s;
cin >> s;
if (s[0] == '0') {
if (k % 2) {
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] == '1') {
cout << i + 1 << "\n";
return;
}
}
} else {
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] == '0') {
cout << i + 1 << "\n";
return;
}
}
}
} else {
if (k % 2) {
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] == '0') {
cout << i + 1 << "\n";
return;
}
}
} else {
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] == '1') {
cout << i + 1 << "\n";
return;
}
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int T;
cin >> T;
while (T--) {
solve();
}
return 0;
}
Contest: 16/2/24 (Tree)
1. Tree : Top View
Given a pointer to the root of a binary tree, print the top view of the binary tree.
The tree as seen from the top the nodes, is called the top view of the tree.
For example :
1
\
2
\
5
/ \
3 6
\
4
Top View :
Complete the function and print the resulting values on a single line separated by
space.
Input Format
}
Constraints
Nodes in the tree
Output Format
Sample Input
1
\
2
\
5
/ \
3 6
\
4
Sample Output
1256
Explanation
1
\
2
\
5
/ \
3 6
\
4
From the top, only nodes are visible.
Solution:
/*
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
*/
queue<pair<Node*, int>> q;
map<int, int> hdMap;
q.push({root, 0});
while (!q.empty()) {
pair<Node*, int> front = q.front();
q.pop();
if (hdMap.find(hd) == hdMap.end()) {
hdMap[hd] = current->data;
}
if (current->left) {
q.push({current->left, hd - 1});
}
if (current->right) {
q.push({current->right, hd + 1});
}
}
Input Format
}
Constraints
• No. of nodes in the tree 500
Output Format
Return the root of the binary search tree after inserting the value into the tree.
Sample Input
4
/\
2 7
/\
1 3
Sample Output
4
/ \
2 7
/\ /
1 36
Solution:
/*
Node is defined as
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
*/
if(root==NULL){
return new Node(data);
}
if(root->data > data){
root->left = insert(root->left,data);
}
else{
root->right = insert(root->right,data);
}
return root;
}
Given the root node of a binary tree, can you determine if it's also a binary search tree?
Complete the function in your editor below, which has parameter: a pointer to the root of
a binary tree. It must return a boolean denoting whether or not the binary tree is a binary
search tree. You may have to write one or more helper functions to complete this
challenge.
Input Format
You are not responsible for reading any input from stdin. Hidden code stubs will assemble
a binary tree and pass its root node to your function as an argument.
Constraints
•
Output Format
You are not responsible for printing any output to stdout. Your function must
return true if the tree is a binary search tree; otherwise, it must return false. Hidden code
stubs will print this result as a Yes or No answer on a new line.
Sample Input
Sample Output
No
Solution:
/* Hidden stub code will pass a root argument to the function below.
Complete the function to solve the challenge. Hint: you may want to write
one or more helper functions.
inOrderTraversal(root->left, elements);
elements.push_back(root->data);
inOrderTraversal(root->right, elements);
}
return true;
}
You are given pointer to the root of the binary search tree and two values and . You need
to return the lowest common ancestor (LCA) of and in the binary search tree.
In the diagram above, the lowest common ancestor of the nodes and is the node . Node is
the lowest node which has nodes and as descendants.
Function Description
Complete the function lca in the editor below. It should return a pointer to the lowest
common ancestor node of the two values given.
Input Format
The first line contains an integer, , the number of nodes in the tree.
The second line contains space-separated integers representing values.
The third line contains two space-separated integers, and .
To use the test data, you will have to create the binary search tree yourself. Here on the
platform, the tree will be created for you.
Constraints
The tree will contain nodes with data equal to and .
Output Format
Return the a pointer to the node that is the lowest common ancestor of and .
Sample Input
6
423176
17
and .
Sample Output
[reference to node 4]
Explanation
LCA of and is , the root in this case.
Return a pointer to the node.
Solution:
/*The tree node has data, left child and right child
class Node {
int data;
Node* left;
Node* right;
};
*/
if(root==NULL){
return NULL;
}
if(root->data > v1 && root->data > v2){
return lca(root->left,v1,v2);
}
if(root->data < v1 && root->data < v2){
return lca(root->right,v1,v2);
}
return root;
}