0% found this document useful (0 votes)
15 views84 pages

Contest Solutions

The document outlines several programming problems and their solutions, including generating patterns, rotating arrays, checking balanced brackets, removing duplicates from linked lists, calculating the height of binary trees, and determining happy numbers. Each problem is accompanied by input and output formats, sample inputs, and C++ code solutions. Additionally, it includes problems related to popular numbers and anomaly detection in data.

Uploaded by

hemitrana2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views84 pages

Contest Solutions

The document outlines several programming problems and their solutions, including generating patterns, rotating arrays, checking balanced brackets, removing duplicates from linked lists, calculating the height of binary trees, and determining happy numbers. Each problem is accompanied by input and output formats, sample inputs, and C++ code solutions. Additionally, it includes problems related to popular numbers and anomaly detection in data.

Uploaded by

hemitrana2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Contest 1: (warmup)

1. Number star

We have to print the pattern as given in the below example.

Input Format

The first line will contain an integer ‘N’ that is the total number of rows.

Constraints

0 <= n <= 100

Output Format

print the pattern of N lines.

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;

int main() { int N, d; cin >> N >> d;


vector<int> v(N); for (size_t i = 0;
i < v.size(); ++i) { cin >> v[i];
}
d = d % N; for (int i =
d; i < N; ++i) cout <<
v[i] << ' ';
for (int i = 0; i < d; ++i)
cout << v[i] << ' ';
/* Enter your code here. Read input from STDIN. Print output to STDOUT */ return
0;
}

3. Balanced brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ].


Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {)
occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three
types of matched pairs of brackets: [], {}, and ().
A matching pair of brackets is not balanced if the set of brackets it encloses are not
matched. For example, {[(])} is not balanced because the contents in between { and } are
not balanced. The pair of square brackets encloses a single, unbalanced opening bracket, (,
and the pair of parentheses encloses a single, unbalanced closing square bracket, ].
By this logic, we say a sequence of brackets is balanced if the following conditions are met:
• It contains no unmatched brackets.

• The subset of brackets enclosed within the confines of a matched pair of


brackets is also a matched pair of brackets.

Given strings of brackets, determine whether each sequence of brackets is balanced. If a


string is balanced, return YES. Otherwise, return NO.
Function Description
Complete the function isBalanced in the editor below.

isBalanced has the following parameter(s):

• string s: a string of brackets


Returns
• string: either YES or NO
Input Format
The first line contains a single integer , the number of strings.
Each of the next lines contains a single string , a sequence of brackets.
Output Format
For each string, return YES or NO.
Sample Input
STDIN Function

----- --------

3 n=3

{[()]} first s = '{[()]}'

{[(])} second s = '{[(])}'

{{[[(())]]}} third s ='{{[[(())]]}}'


Sample Output
YES
NO
YES

Solution:

#include <bits/stdc++.h>

using namespace std;

string isBalanced(string s) { std::vector <


char> stack; bool flag = false; for(int i = 0;
(i < s.length()) && !flag; i++){

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 format for each test case is as follows:

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;
}
};

class SinglyLinkedList { public:


SinglyLinkedListNode *head;
SinglyLinkedListNode *tail;

SinglyLinkedList() { this-
>head = nullptr; this->tail =
nullptr;
}

void insert_node(int node_data) {


SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data);

if (!this->head) { this-
>head = node;
} else { this->tail->next =
node;
}

this->tail = node;
}
};

void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) {


while (node) { fout << node->data; node = node->next;

if (node) {
fout << sep;
}
}
}

void free_singly_linked_list(SinglyLinkedListNode* node) {


while (node) {
SinglyLinkedListNode* temp = node; node
= node->next;

free(temp);
}
}

SinglyLinkedListNode* removeDuplicates(SinglyLinkedListNode* llist) {


SinglyLinkedListNode *curr = llist;
while (curr != NULL) {
SinglyLinkedListNode *next = curr->next; while
(next != NULL && next->data == curr->data)
next = next->next;
curr->next = next; curr = next; if
(next != NULL) next = next->next;
}
return llist;
}

int main()
{
ofstream fout(getenv("OUTPUT_PATH"));

int t;
cin >> t; cin.ignore(numeric_limits<streamsize>::max(),
'\n');

for (int t_itr = 0; t_itr < t; t_itr++) {


SinglyLinkedList* llist = new SinglyLinkedList();

int llist_count; cin >> llist_count;


cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int i = 0; i < llist_count; i++) { int llist_item; cin
>> llist_item;
cin.ignore(numeric_limits<streamsize>::max(), '\n');

llist->insert_node(llist_item);
}

SinglyLinkedListNode* llist1 = removeDuplicates(llist->head);


print_singly_linked_list(llist1, " ", fout);
fout << "\n";

free_singly_linked_list(llist1);
}

fout.close();

return 0;
}

5. Height of a binary tree

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.

getHeight or height has the following parameter(s):

• root: a reference to the root of a binary tree.


Note -The Height of binary tree with single node is taken as zero.
Input Format
The first line contains an integer , the number of nodes in the tree.
Next line contains space separated integer where th integer denotes node[i].data.
Note: Node values are inserted into a binary search tree before a reference to the tree's
root node is passed to your function. In a binary search tree, all nodes on the left branch of
a node are less than the node value. All values on the right branch are greater than the
node value.
Output Format

Your function should return a single integer denoting the height of the binary tree.

Solution:

#include <bits/stdc++.h>

using namespace std;

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) {

std::cin >> data;

root = myTree.insert(root, data);


}

int height = myTree.height(root);

std::cout << height;

return 0;
}
Contest 2: (arrays)
1: seema and birju

Write an algorithm to determine if a number of burgers (represented as n) makes Birju


and Seema happy.

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.

Return true if n is a happy "number of burgers", and false if not.

Input Format

integer n

Constraints

1 <= n <= 2^31 - 1

Output Format

Return true if n is a happy number, and false if not.

Sample Input 0
19
Sample Output 0
true
Explanation 0
• 1^2 + 9^2 = 82

• 8^2 + 2^2 = 68

• 6^2 + 8^2 = 100

• 1^2 + 0^2 + 0^2 = 1


Solution:

#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

2. 0 <= arr[i] <= 105

Output Format

the integer which occurs more than 25% of the time

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

integer array nums of length n and an integer target

Constraints
• 1 <= nums.length == n <= 50

• -50 <= nums[i], target <= 50

Output Format

return the number of pairs

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

• (0, 2) since 0 < 2 and nums[0] + nums[2] = 1 < target

• (0, 4) since 0 < 4 and nums[0] + nums[4] = 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;

while (left < right) {


if (nums[left] + nums[right] < target)
{
count += right - left;
left++;
} else { right-
-;
}
}

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.

Return the positive integer x. If there is no such integer, return -1.

Input Format

an array

Constraints
• 1 <= nums.length <= 1000

• -1000 <= nums[i] <= 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

3 is the only valid k we can find in the array.

Solution:

int findMaxK ( vector < int > & nums ) { map< int ,
int > mp ;
for ( auto it : nums ) mp [it]++;

int ans = INT_MIN ; bool


gotAnsr = false ;

for ( int i= 0 ; i< nums . size () ; i++ ){

if ( nums [i] > 0 ) { if ( mp . find ( 0 - nums [i] ) != mp .


end () ){

ans = max ( ans, nums [i] ); gotAnsr =


true ;
}
}
}

if ( gotAnsr ) return ans ; return -


1 ; }

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

2. -10 <= nums[i] <= 10

3. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
Output Format

the maximum product

Sample Input 0
2 3 -2 4
Sample Output 0
6
Explanation 0

[2,3] has the largest product 6.

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.

The overall run time complexity should be O(log (m+n)).

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

integer that is a median

Sample Input 0
13
2
Sample Output 0
2.00000
Explanation 0

merged array = [1,2,3] and median is 2.

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

// Optimized Using: Two Pointer with Extra Space


// Time Complexity: O(m+n)
// Space Complexity: O(m+n)
class Solution { public: double findMedianSortedArrays ( vector < int > & nums1 , vector
< int > &
nums2 ) {

// 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 ;

// Initialize a new array vector< int > v


(n1+n2, 0 );

while (i<n1&&j<n2)
{ if ( nums1 [i]<= nums2 [j]) v [++lastindex]=
nums1 [i++];
else v [++lastindex]= nums2 [j++];
}

while (i<n1) v [++lastindex]= nums1


[i++];
while (j<n2) v [++lastindex]= nums2
[j++];

// Return the result int


n=n1+n2;
return n% 2 ? v [n/ 2 ]:( v [n/ 2 ]+ v [n/ 2 - 1 ])/ 2.0 ;

} };

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.

Return the minimum number of substrings in such a partition.

Note that each character should belong to exactly one substring in a partition.

Input Format

a string

Constraints
• 1 <= s.length <= 105

• s consists of only English lowercase letters.

Output Format

minimum number of substrings needed

Sample Input 0
abacaba
Sample Output 0
4
Explanation 0
• Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").

• It can be shown that 4 is the minimum number of substrings needed.


Solution:

#include <bits/stdc++.h>
using namespace std;

int main() {
string s;
cin >> s;

if (s == "") {
cout << 0;
return 0;
}

unordered_set<char> uniqueChars; int


substringCount = 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;
}

3. Matrix binary search

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

a matrix and a search key

Constraints

m == matrix.length n == matrix[i].length 1 <= m, n <= 100 -104 <= matrix[i][j], target <=
104

Output Format

the index in form of (row,column)

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;

// Input values into the vector of


vectors std::string line; while
(std::getline(std::cin, line)) {
std::istringstream lineStream(line);
std::vector<int> row;
int num; while (lineStream
>> num) {
row.push_back(num);
}
ar.push_back(row);
}

int m = ar.size(); int n = ar[0].size(); int top = 0,


left = 0, bottom = m - 2, right = n - 1; int key =
ar[m - 1][0]; int i = 0;

while (top <= bottom) {


i = (top + bottom) / 2; if (key <=
ar[i][right] && ar[i][left] <= key) {
break;
} else if (ar[i][right] > key) {
bottom = i - 1;
} else { top =
i + 1;
}
}

while (left <= right) { int


mid = (left + right) / 2; if
(ar[i][mid] == key) {
std::cout << "(" << i << "," << mid << ")\n";
return 0;
} else if (ar[i][mid] < key) {
left = mid + 1;
} else if (ar[i][mid] > key) {
right = mid - 1;
}
}

std::cout << "-1\n";


return 0;
}

4. 2 lanes subway surfer

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

1 <= array.length == n <= 50

Output Format

the maximum sum

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

X = { 3, 6, 7, 8, 10, 12, 15, 18, 100 }

Y = { 1, 2, 3, 5, 7, 9, 10, 11, 15, 16, 18, 25, 50 }

The path is: 1 —> 2 —> 3 —> 6 —> 7 —> 9 —> 10 —> 12 —> 15 —> 16 —> 18 —> 100

The sum is 199

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;

// loop till `arr1` and `arr2` are empty while (i <


arr1.size() && j < arr2.size()) { // to handle the
duplicate elements in `arr1` while (i < arr1.size() - 1
&& arr1[i] == arr1[i + 1]) {
sum_x += arr1[i++];
}

// to handle the duplicate elements in `arr2`


while (j < arr2.size() - 1 && arr2[j] == arr2[j + 1])
{
sum_y += arr2[j++];
}

// 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++;
}

else // if (arr1[i] == arr2[j])


{
// consider the maximum sum and include the current cell's value sum
+= max(sum_x, sum_y) + arr1[i];
// move both indices by 1 position
i++, j++;

// reset both sums


sum_x = 0, sum_y = 0;
}
}

// process the remaining elements of `arr1` (if any)


while (i < arr1.size()) {
sum_x += arr1[i++];
}

// process the remaining elements of `arr2` (if any)


while (j < arr2.size()) {
sum_y += arr2[j++];
}

sum += max(sum_x, sum_y); return


sum;
}

int main() {
std::string line;

// Read the first line


std::getline(std::cin, line);
std::istringstream iss1(line);
std::vector<int> arr1; int
num1; while (iss1 >>
num1) {
arr1.push_back(num1);
}

// Read the second line


std::getline(std::cin, line);
std::istringstream iss2(line);
std::vector<int> arr2; int
num2; while (iss2 >>
num2) {
arr2.push_back(num2);
}

int sum = subwaySurf(arr1, arr2);


std::cout << sum << std::endl; return
0;
}

5. Matrix layer rotation


You are given a 2D matrix of dimension and a positive integer . You have to rotate the
matrix times and print the resultant matrix. Rotation should be in anti-clockwise
direction.
Rotation of a matrix is represented by the following figure. Note that in one rotation, you
have to shift elements by one step only.

It is guaranteed that the minimum of m and n will be even.

As an example rotate the Start matrix by 2:

Start First Second

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.

matrixRotation has the following parameter(s):

• int matrix[m][n]: a 2D array of integers


• int r: the rotation factor
Prints
It should print the resultant 2D integer array and return nothing. Print each row on a
separate line as space-separated integers.
Input Format
The first line contains three space separated integers, , , and , the number of rows and
columns in , and the required rotation.
The next lines contain space-separated integers representing the elements of a row of .
Sample Input
Sample Input #01
STDIN Function

----- --------

442 rows m = 4, columns n = 4, rotation factor r = 2

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

Sample Output #01


3 4 8 12
2 11 10 16
1 7 6 15
5 9 13 14
Solution:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

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];
}
}

int numRings = min(M,N)/2;


for(int i = 0; i < numRings; i++) {
// Subtract the number of 360 degree rotations from R
// A 360 degree rotation = rotating the same number of times as the perimeter of
the current ring int numRotations = R%(2*(M + N - 4*i) - 4); for(int
rotation = 0; rotation < numRotations; rotation++) {
// Rotate the ring (see the clockwise algorithm for an in-depth example of
how this is done)
// Rotate top row for(int j = i; j <
N-i-1; j++) { int tmp =
matrix[i][j]; matrix[i][j] =
matrix[i][j+1]; matrix[i][j+1] =
tmp;
}
// Rotate right column for(int j = i; j < M-
i-1; j++) { int tmp = matrix[j][N-i-1];
matrix[j][N-i-1] = matrix[j+1][N-i-1];
matrix[j+1][N-i-1] = tmp;
}
// Rotate bottom row
for(int j = N-i-1; j > i; j--) { int tmp =
matrix[M-i-1][j]; matrix[M-i-1][j]
= matrix[M-i-1][j-1]; matrix[M-i-
1][j-1] = tmp;
}
// Rotate left column for(int j =
M-i-1; j > i+1; j--) { int tmp =
matrix[j][i]; matrix[j][i] =
matrix[j-1][i]; matrix[j-1][i] =
tmp;
}
}
}
// Output final matrix for(int i = 0; i
< M; i++) { for(int j = 0; j < N; j++) {
cout<<matrix[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
Contest: 12/1/24 (revision)
1. UNO
You have N UNO number cards placed in front of you on the desk. The i th card has the
number Ai written on it.

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.

• you are given a permutation P.

• 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.

• Note: An array P is said to be a permutation of {1, 2, 3, ..., N} if P contains each


element of {1, 2, 3,..., N} exactly once.

Input Format
• • The first line of input will contain a single integer T, denoting the number of
test cases.

• Each test case consists of two lines of input.

• • 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

• 2 <= N <= 10^5

• 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;

int main() { // your code


goes here int
t,n,a,b,num; for(cin>>t;t-
-;){ cin>>n; for(int
i=0;i<n;++i){
cin>>num; if(num
== 1) a = i;
else if(num == n) b = i;
}
cout << a + (n-b-1) - (b<a) << endl;
}
return 0;
}

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.

The i th person prefers to be in a group of exactly Pi people (including himself). A person


who is not in a group of preferred size gets upset. Find whether Ashwin sir would be able
to assign every person to a group such that everyone remains happy.

Input Format
• • The first line of input will contain a single integer T. denoting the number of
test cases.

• • Each test case consists of multiple lines of input.

• • 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

• 2 < N < 10^5


• 2 <= Pi <= N

• Sum of N over all test cases does not exceed 10^5.

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;

void solve(){ int people;


cin>>people;
vector<int>v(people);
for(int i=0;i<people;i++){
cin>>v[i];
}

vector<int>ans(people+1,0);
for(int i=0;i<v.size();i++){
ans[v[i]]++;
}

int flag=0; for(int


i=0;i<ans.size();i++){ if(ans[i]!=0
&& (ans[i]%i!=0)){
cout<<"NO"<<endl;
flag=1; break;
} } if(flag!=1){
cout<<"YES"<<endl;
} } int main()
{ int n;
cin>>n;
while(n--){
solve();
}
return 0;
}

4. Binary string alteration


• A binary string is called alternating if no two adjacent characters of the string
are equal. Formally, a binary string T of length M is called alternating if Ti !=
Ti+1 for each 1 < i < M.

• 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 first line of each test case contains an integer N.

• • The second line of each test case contains the binary string S.

Constraints
• • 1 <= T <= 10^4

• • 1 ≤ N ≤ 10^5

• • S contains only the characters 0 and 1.

• • Sum of N over all test cases does not exceed 2*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 2: The given string S = 1010 is an alternating string of length 4.

• Test case 3: The length of the longest alternating substring is 1 for any
rearrangement of S = 0000.

• Test case 4: One possible rearrangement of S is 1101011, which has an


alternating substring of length 5 (the substring starting at index 2 and ending at
index 6).

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.

A closing HTML tag must:

- Start with '</'


- End with '>'
- Have only lower-case alpha-numeric characters as its body (between '</' and '>'). That is, each
character of the body should either be a digit or a lower-case English letter.
- Have a non-empty body.

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.

Kumandra city's language sentence structure:

• the sentence contains only the characters from the two given languages.

• each word contains only characters from a single language

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

• 1 <= |Si| ≤ 100 for each valid i

• the sum of lengths of all the strings on the input does not exceed 105

• each string contains only lowercase and uppercase English letters

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.

• Our current understanding of physics gives us a way to predict how the


particles will be spaced out, if we know their charges. Two adjacent particles
will be separated by 1 unit if they have opposite charges, and 2 units if they
have the same charge.
• a scientist is doing physics experiments on subatomic particles. He is testing the
hypothesis by having N particles in a row, and he will change the charge of a
particle K times. In the i-th update, he will change the charge of the Qi-th
particle. After each update, find the distance between the first and last particle.

• Note: Each update is persistent for further updates.

Input Format
• • The first line contains an integer T, the number of test cases. Then the test
cases follow.

• • Each test case contains three lines of input.

• • The first line contains two integers N, K.

• • 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

• • S contains only 0 and 1 characters.

• • 1 <= Qi <= N

• • The sum of K over all testcases is at most 2x10^5

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 main() { int N; cin


>> N; vector<int> A(N);
for(int i = 0; i < N; i++) {
cin >> A[i];
}

int start = 0;

vector<int> D(N+1, 0);


for(int i = 0; i < N; i++) {
if(A[i] <= i) {
start++;
D[i-A[i]]--;
D[i]++;
} else {
D[i-A[i]+N]--;
D[i]++;
}
}

int best = start; int


bi = 0;
int cur = start; for(int i
= 0; i < N; i++) { if(cur
> best) { best = cur;
bi = i;
}
cur += D[i];
}

cout << (bi+1) << endl;


}
Contest: 26/1/24 (revision 3)
1. Difference of pairs
• Given an array A of N integers and an integer B.

• 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.

• Each test case consists of multiple lines of input.

• • The first line of each test case contains two space-separated integers N and B.

• • The next line contains N space-separated integers representing array A.

Constraints
• • 1 <= T <= 100

• • 1 ≤ N ≤ 10^5

• • -10^6 <= B <= 10^6

• • -10^6 <= Ai <= 10^6

• • The sum of N over all test cases won't exceed 2*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;

while (T--) { int N,


B; std::cin >> N >> B;
B = std::max(B, -B);
std::vector<int> A(N);

for (int i = 0; i < N; i++) {


std::cin >> A[i];
}

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

Input an integer N and flip the most significant and least


significant bit
- Print the number.
- Least Significant Bit
• The least significant bit (LSB) is the rightmost bit in a binary representation of a
number. In binary, each digit or bit represents a power of 2. The least significant bit
represents the smallest power of 2 in the binary number, typically 2^0 or 1.

• For example, in the 8-bit binary number 11010101, the least significant bit is the
rightmost bit, which is 1 in this case.

• Changing the least significant bit from 0 to 1 or from 1 to 0 results in a change of


the least amount in the value of the number. This property is often used in
various applications, such as error detection, cryptography, and certain data
encoding techniques.

-
- 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

a single decimal number

Constraints
0 <= N <= 100

Output Format

a modified decimal number

Sample Input 0
6
Sample Output 0
3
Sample Input 1
7
Sample Output 1
2
Solution:
#include <iostream> using
namespace std;

int main() { // your


code goes here
int n; cin>>n;

// fliping the least significant bit


n = n^1;

// finding the position of most significant bit


int pos = 0; int n1 = n; while(n1!=0)
{

n1 /=2;
pos++;

pos--;

// fliping the most significant bit


n = n^(1<<pos); cout<<n<<"\n";
return 0;

3. Pizza party

#include <bits/stdc++.h>
using namespace std;

long long gcd(long long a,long long b){

if(b%a == 0){
return a;
}

return gcd(b%a,a);

int main() {

// your code goes here

long long t,n,k,lcm;

cin >> t;

while(t--) {

cin >> n >> k;

lcm = (k*n)/gcd(min(n,k),max(n,k)); cout

<< lcm/k << endl;

return 0;

}
4. Array
manipulation
• Happy has a permutation P of length 2*N. He can perform the following
operation on P:

• Select an index i (1 <= i <= 2*N) and swap Pi and Pi+1.

• 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.

• Note: A permutation of length N is an array where every integer from 1 to N


occurs exactly once.

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

• • 1 <= N <= 10^5

• . P is a permutation of length 2*N

• • The sum of N over all test cases won't exceed 2*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]

• Apply operation at i = 2: [2, 3, 1, 4]→[2,1,3,4]

• Test case 2: P is already good.

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;

Contest: 2/2/24 (Linkedlist)

1. Find Merge Point of Two Lists

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;

// Traverse both lists until they meet at the merge point


while (current1 != current2) {
// Move to the next node in each list
current1 = current1->next ? current1->next : head2;
current2 = current2->next ? current2->next : head1;
}

// Return the value of the merge node


return current1->data;
}

2. Compare two linked lists

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.

The output is handled by the code in the editor and it is as follows:

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;

3. Insert a node at a specific position in a linked list


Given the pointer to the head node of a linked list and an integer to insert at a certain
position, create a new node with the given integer as its data attribute, insert this node at
the desired position and return the head node.

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.

Insert a node at position 1 with. The new list is


Function Description Complete the function insertNodeAtPosition in the editor below. It
must return a reference to the head node of your finished list.

insertNodeAtPosition has the following parameters:


• head: a SinglyLinkedListNode pointer to the head of the list
• data: an integer value to insert as data in your new node
• position: an integer position to insert the new node, zero based indexing
Returns
• SinglyLinkedListNode pointer: a reference to the head of the revised list
Input Format
The first line contains an integer n, the number of elements in the linked list.
Each of the next n lines contains an integer SinglyLinkedListNode[i].data.
The next line contains an integer data, the data of the node that is to be inserted.
The last line contains an integer position.
Sample Input
3
16
13
7
1
2
Sample Output
16 13 1 7

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;
* };
*
*/

SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* llist, int


data, int position) {
SinglyLinkedListNode* newnode = new SinglyLinkedListNode(data);
SinglyLinkedListNode* temp = llist;
while(--position){
temp = temp->next;
}
newnode->next = temp->next;
temp->next = newnode;

return llist;
}

4. Merge two sorted linked lists


Given pointers to the heads of two sorted linked lists, merge them into a single, sorted
linked list. Either head pointer may be null meaning that the corresponding list is empty.

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 format for each test case is as follows:

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;

// Merge the lists until one of them is exhausted


while (head1 && head2) {
SinglyLinkedListNode* newNode = NULL;

if (head1->data < head2->data) {


newNode = create_singly_linked_list_node(head1->data);
head1 = head1->next;
} else {
newNode = create_singly_linked_list_node(head2->data);
head2 = head2->next;
}

// Append the new node to the merged list


if (!mergedHead) {
mergedHead = newNode;
mergedTail = newNode;
} else {
mergedTail->next = newNode;
mergedTail = newNode;
}
}

// Append the remaining nodes from the non-empty list


if (head1) {
if (!mergedHead) {
mergedHead = head1;
} else {
mergedTail->next = head1;
}
} else if (head2) {
if (!mergedHead) {
mergedHead = head2;
} else {
mergedTail->next = head2;
}
}

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

• • Sum of N over all test cases does not exceed 5.10^5

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.

For the third test case, he cannot make any jumps.

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;

char res = s[0];


int cnt = 0;
for (int i = 1; i < n; i++) {
if (res != s[i]) {
cnt++;
res = s[i];
}
}
if (cnt < k) {
cout << -1 << "\n";
return;
}

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

You are given a function,

void topView(node * root) {

}
Constraints
Nodes in the tree
Output Format

Print the values on a single line separated by space.

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;
}
};

*/

void topView(Node * root) {


if (root == nullptr) {
return;
}

queue<pair<Node*, int>> q;
map<int, int> hdMap;

q.push({root, 0});
while (!q.empty()) {
pair<Node*, int> front = q.front();
q.pop();

Node* current = front.first;


int hd = front.second;

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});
}
}

for (auto it = hdMap.begin(); it != hdMap.end(); ++it) {


cout << it->second << " ";
}
}

2. Binary Search Tree : Insertion


You are given a pointer to the root of a binary search tree and values to be inserted into
the tree. Insert the values into their appropriate position in the binary search tree and
return the root of the updated binary tree. You just have to complete the function.

Input Format

You are given a function,

Node * insert (Node * root ,int data) {

}
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

The value to be inserted is 6.

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;
}
};

*/

Node * insert(Node * root, int data) {

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;
}

3. Is This a Binary Search Tree?


For the purposes of this challenge, we define a binary tree to be a binary search tree with
the following ordering requirements:
• The value of every node in a node's left subtree is less than the data value of
that node.
• The value of every node in a node's right subtree is greater than the data value
of that node.

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.

The Node struct is defined as follows:


struct Node {
int data;
Node* left;
Node* right;
}
*/
void inOrderTraversal(Node* root, vector<int>& elements) {
if (root == nullptr) {
return;
}

inOrderTraversal(root->left, elements);
elements.push_back(root->data);
inOrderTraversal(root->right, elements);
}

bool checkBST(Node* root) {


vector<int> elements;
inOrderTraversal(root, elements);

// Check if the elements are in sorted order


for (size_t i = 1; i < elements.size(); ++i) {
if (elements[i] <= elements[i - 1]) {
return false;
}
}

return true;
}

4. Binary Search Tree : Lowest Common Ancestor

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.

lca has the following parameters:


- root: a pointer to the root node of a binary search tree
- v1: a node.data value
- v2: a node.data value

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;
};

*/

Node *lca(Node *root, int v1,int v2) {

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;
}

You might also like