Tuesday, August 2, 2022

CODING ASSESSMENT ( TCS NQT)

 

FACEPREP CODING ASSESSMENT

Q1.

Find the area of a triangle and check whether the area is palindrome or not.

Input Format:

First line of input contains three integers with space separation.

Output Format:

First line an integer i.e. area of a triangle

Second line prints either Palindrome or Not Palindrome

Sample Input1:

4 6 8

Sample Output1:

11

Palindrome

Sample Input2:

22 22 22

Sample Output2:

209

Not Palindrome

SOLUTION IN C:

#include<stdio.h>

#include<math.h>

int main(){

    int a,b,c,s,area,temp,rev=0;

    scanf("%d %d %d",&a,&b,&c);

    s = (a+b+c)/2;

    area = (int)sqrt(s*(s-a)*(s-b)*(s-c));

    temp = area;

    while(temp){

        rev = rev*10+temp%10;

        temp /= 10;

    }

    if(rev==area){

        printf("%d\nPalindrome",area);

    }else{

        printf("%d\nNot Palindrome",area);

    }

    return 0;

}

SOLUTION IN PYTHON:

import math

a,b,c = map(int,input().split())

s = (a+b+c)//2

area = int(math.sqrt(s*(s-a)*(s-b)*(s-c)))

if str(area)==str(area)[::-1]:

    print(area,"\nPalindrome")

else:

    print(area,"\nNot Palindrome")

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Q2.

Write a program to find whether the given string is the anagram of the first string.

Sample Input 1:

eat ate

Sample Output 1:

Anagram

Sample Input 2:

eat abc

Sample Output 2:

Not Anagram

SOLUTION IN C:

#include<stdio.h>

#include<string.h>

void sortStringChars(char*);

int main(){

    char string1[30],string2[30];

    scanf("%s %s",string1,string2);

    sortStringChars(string1);

    sortStringChars(string2);

    if(strcmp(string1,string2)==0){

        printf("Anagram");

    }else{

        printf("Not Anagram");

    }

    return 0;

}

 

void sortStringChars(char *s){

    int i,j;

    char temp;

    for(i=0;i<strlen(s)-1;i++){

        for(j=i+1;j<strlen(s);j++){

            if(s[i]>s[j]){

                temp = s[i];

                s[i] = s[j];

                s[j] = temp;

            }

        }

    }

}

SOLUTION IN PYTHON:

string1, string2 = input().split()

string1 = sorted(string1)

string2 = sorted(string2)

if string1==string2:

    print("Anagram")

else:

    print("Not Anagram")

 

 

 

 

 

 

Q3.

Sita has a love for Dairy milk. She has bought a huge Dairy milk chocolate bar which contains N squares arranged in a row. Each of the squares has a tastiness level which is denoted by an array A[]. Sita can eat the first or the last square of the chocolate bar at once. Sita has a sister who too loves chocolates and she demands the final chocolate square that is left over. Now, Sita, being greedy, eats all the tastier squares possible. Determine the tastiness level of the square which her sister gets.

Input format: 

First line of input contains a single integer T denoting the number of test cases.

The first line of each test case contains an integer N.

The second line contains N space-separated integers denoting the array A.

Output format: 

For each test case, print the required answer in a new line.

Constraints : 

1 <= T <= 100

1 <= N <= 250

1 <= A[i] <= 1000

Sample Input1: 

3

5

5 3 1 6 9

6

2 6 4 8 1 6

4

2 2 2 2

Sample Output1: 

1

1

2

 

SOLUTION IN C:

#include<stdio.h>

int main(){

    int t,n,ary[30],result[10],min,i,j;

    scanf("%d",&t);

    for(i=0;i<t;i++){

        scanf("%d",&n);

        for(j=0;j<n;j++){

            scanf("%d",&ary[j]);

        }

        min = ary[0];

        for(j=0;j<n;j++){

            if(min>ary[j]){

                min = ary[j];

            }

        }

        result[i] = min;

    }

    for(i=0;i<t;i++){

        printf("%d",result[i]);

        if(i<t-1){

            printf("\n");

        }

    }

    return 0;

}

SOLUTION IN PYTHON:

t = int(input())

result = []

for i in range(t):

    n = int(input())

    ary = list(map(int,input().split()))[:n]

    result.append(min(ary))

for i in range(t):

    print(result[i],end='')

    if i<t-1:

        print()

 

 

 

 

Q4.

In this lockdown a family of N members decided to play a game the rules of which are

  • All N members are made to sit uniformly in a circle (ie. from 1 to N in clockwise direction).
  • The game start with the person sitting at first position.
  • A song is played in the background. The lyrics of the song are denoted by a string which consists of only letters 'x' and 'y'. Assume that each lyric of the song is a single letter. 
  • If the lyric 'x' occurs in the song, the member who is currently holding the Parcel passes it on to the next member. This passing takes place in clockwise direction.
  • If the lyric 'y' occurs in the song, the member who is currently holding the Parcel loses his/her chances of winning the game. He/she hands over the parcel to the next member (in clockwise direction) and moves out.
  • The game continues until a single member survives in the end. He/she will be the winner of the game.
  • Note that the song repeats continuously ie. while the game is going on, if at all the song ends, the stereo system will automatically start playing the song from the start without any delay.

You have to find out the member who wins the game.

Input Format:

The input consists of 2 lines. The first line consists of N, the member of family in the class. The next line consists of a string denoting the lyrics of the song the teacher plays.

Output Format:

Print a single integer denoting the roll number of the student who wins the game.

Constraints :

2≤N≤100000

1≤|S|≤10000, where |S| denotes the length of the input string. It is guaranteed that at least 1 lyric in the song will be a 'y'

Sample Input1:

3

xyx

Sample Output1:

1

Explanation:

Starting from 1 lyrics: 'x' therefore he passes the ball to 2nd 

2nd turn lyrics: 'y' therefore 2nd member gets out of game and passes to 3rd

3rd turn lyrics: 'x' therefore 3rd passes ball to first.

4th turn lyrics: 'x' passes to 3rd 

5th turn lyrics: 'y' therefore gets eliminated.

Hence person sitting at position 1 won this game. 

Sample Input2:

6

xxyyxy

Sample Output2:

2

SOLUTION IN C:

#include<stdio.h>

int main(){

    int n,members[30],i,j,k;

    char lyric[30];

    scanf("%d\n",&n);

    for(i=0;i<n;i++){

        members[i] = i+1;

    }

    fgets(lyric,30,stdin);

    while(n!=1){

        i = 0;

        for(j=0;lyric[j]!='\0';j++){

            if(lyric[j]=='x'){

                i+=1;

            }else if(lyric[j]=='y' && n!=1){

                i = i%n;

                for(k=i;k<n-1;k++){

                    members[k] = members[k+1];

                }

                n--;

            }

        }

    }

    printf("%d",members[0]);

    return 0;

}

SOLUTION IN PYTHON:

n = int(input())

lyric = input()

members = list(range(1,n+1))

while len(members)!=1:

    i = 0

    for c in lyric:

        if c=='x':

            i += 1

        elif c=='y' and len(members)!=1:

            members.pop(i%len(members))

print(members[0])

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Q5.

Junior High College is holding elections for the next student representative of the college. Due to pandemic, physically casting votes is not possible & the students decided to make an online website for collecting the votes of students. The entire website is built but only the algorithm that finds out who won the election is not coded yet and the student team is not able to figure out the solution so they approach you to solve it. Your task is to find the person with majority votes.

Input format:

The first line indicates the total number of votes

The following line contains space separated vote of each person to the candidate number

Output format:

Print the candidate number with majority of votes

Sample Input:

7

1 1 3 1 1 2 2

Sample Output:

1

SOLUTION IN C:

#include<stdio.h>

int main() {

    int n,votes[100],maxCount=0,count,candidate,i,j;

    scanf("%d",&n);

    for(i=0;i<n;i++){

        scanf("%d",&votes[i]);

    }

    for(i=0;i<n-1;i++){

        count = 1;

        for(j=i+1;j<n;j++){

            if(votes[i]==votes[j]){

                count++;

            }

        }

        if(maxCount<count){

            maxCount=count;

            candidate = votes[i];

        }

    }

    printf("%d",candidate);

    return 0;

}

SOLUTION IN PYTHON:

noOfVotes = int(input())

votes = list(map(int,input().split()))[:noOfVotes]

maxCount = None

candidateNumber = None

for ele in votes:

    if maxCount==None or maxCount<votes.count(ele):

        maxCount = votes.count(ele)

        candidateNumber = ele

print(candidateNumber)

 

 

 

 

 

 

QUESTION 6

 

Time spent 29m 29s

Not Attempted 0

Given N elements and the task is to implement a stack which removes and returns the maximum frequency element on every pop operation. If there’s a tie in the frequency then the topmost highest frequency element will be returned.

pop will work only if there is minimum one element present inside the stack.

 

Input Format :

First line of input will contains two integers n - (no of elements to push inside the stack) and m - (no of elements to pop from the stack).

Next line will contains n space separated integers to be inserted in the stack.

 

Output Format :

Print the maximum frequency element on every pop operation in a new line and remove it from the stack.

 

Sample Input :

5 2

4 6 7 6 8

 

Sample Output :

6

8

 

Explanation : In this first we will push the element which comes first, so after pushing all the elements we will begin our pop operation 2 times, in first time it will check for that element which have maximum frequency so it will print 6 (frequency of 6 is greater then all other) and removes 6 then after in second pop operation it will check for max frequency element and when the frequency are same then it will check who comes first, in that similar manner it will print 8.

 

Input

5 2 4 6 7 6 8

Output

6
8

 

#include <bits/stdc++.h>

using namespace std;

int main(){

   int n, m;

   cin >> n >> m;

   unordered_map<int, int> freq;

   unordered_map<int, stack<int>> stacks;

   int max_freq = 0;

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

     int x;

     cin >> x;

     freq[x]++;

     max_freq = max(max_freq, freq[x]);

     stacks[freq[x]].push(x);

   }

   while(m--){

     int to_pop = stacks[max_freq].top();

     cout << to_pop << "\n";

     freq[to_pop]--;

     stacks[max_freq].pop();

     if(stacks[max_freq].empty()) max_freq--;

   }

   return 0;

}

 

 

import collections

 

class FreqStack(object):

    def __init__(self):

        self.freq = collections.Counter()

        self.group = collections.defaultdict(list)

        self.maxfreq = 0

 

    def push(self, x):

        f = self.freq[x] + 1

        self.freq[x] = f

        if f > self.maxfreq:

            self.maxfreq = f

        self.group[f].append(x)

 

    def pop(self):

        x = self.group[self.maxfreq].pop()

        self.freq[x] -= 1

        if not self.group[self.maxfreq]:

            self.maxfreq -= 1

 

        return x

 

n, m = map(int, input().split(" "))

arr = list(map(int, input().strip().split(" ")))

frq_stk = FreqStack()

for i in arr:

    frq_stk.push(i)

 

for i in range(0,m):

    print(frq_stk.pop())

//python

n=int(input())

l=list(map(int,input().split()))[:n]

ele=0

re=0

l1=[]

for i in l:

            if i not in l1:

                        l1.append(i)

                        if re<l.count(i):

                                    re=l.count(i)

                                    ele=i

print(ele)

 

Input

86
39 39 39 88 39 39 60 39 39 39 98 35 39 62 98 73 39 76 40 39 45 94 31 39 93 39 56 39 39 39 49 39 39 11 39 76 39 13 39 39 39 7 39 93 39 39 39 39 39 68 12 14 39 39 39 39 39 35 39 39 39 39 81 39 39 62 52 39 72 38 68 78 71 48 83 32 27 10 81 39 39 44 60 80 39 81

Output

39

 


TEST-22

 

 Given an array of integers, return 1 if you find any combination of four elements in the array whose sum is equal to a given value X, else 0.

Input Format :

First line contains two integers N and X - size of array and given value.

Output Format :

Print 1 if there is any four numbers from the array whose sum is equal to X else 0.

Example Cases :

Input :

8 23

10 2 3 4 5 9 7 8

Output: 1

Explanation : Sum of output is equal to 23,

i.e. 3 + 5 + 7 + 8 = 23.

Input :

8 16

1 2 3 4 5 9 7 8

Output: 1

Explanation : Sum of output is equal to 16,

i.e. 1 + 3 + 5 + 7 = 16.

Constraints:

1 <= N <= 100

-1000 <= K <= 1000

-100 <= A[i] <= 100

Solution:

Cpp:

 

 

 

 

#include <bits/stdc++.h>

using namespace std;

 

void Naive_4SUM(int A[], int n, int S)

{

    

// Select the first element and find other three

for (int i = 0; i < n - 3; i++)

{

    // Select the second element and find other two

    for (int j = i + 1; j < n - 2; j++)

    {

        

        // Select the third element and find the fourth

        for (int k = j + 1; k < n - 1; k++)

        {

            // Find the fourth element

            for (int l = k + 1; l < n; l++)

            if (A[i] + A[j] + A[k] + A[l] == S) //Comparing the sum with S

                cout << "["<<A[i] <<", " << A[j]<< ", " << A[k] << ", " << A[l]<<"]"<<endl;

        }

    }

}

}

 

 

int main()

{

    int nums[] = {10, 2, 3, 4, 5, 9, 7, 8} ;

    int n = sizeof(nums) / sizeof(nums[0]);

    int target = 23;

    Naive_4SUM(nums, n, target);

    return 0;

}

 TEST - 25

All Permutations

"I'm not a fan of having kids memorize formulas, and I'm even less of a fan of pushing them to learn those formulas," says Mr. John, 7th grade Math teacher. Maybe he has got a point. He believes in teaching the logic rather than the formula. Anyway, we aren't here to weigh/debate about his opinions. All we gotta do is help Mr. John and his students by writing an algorithm that can calculate & print all the permutations of a given number in strictly sorted order. Remember, Mr. John is gonna use your algorithm to demonstrate permutations in his next class.

Input Format

The input consists of a string

Output Format

Print all the permutations of the given string

Refer the sample output for formatting

Sample Input:

abc

Sample Output:

abc

acb

bac

bca

cab

cba


python :

from itertools import permutations

def perm(s):

l=permutations(s)

for i in list(l):

print(''.join(i))

s=input()

perm(s)


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

from math import *

from itertools import *

class Solution:

    def find_permutation(self, s):

        l=permutations(s)

        ans=[]

        for e in l :

            st=""

            for i in e :

                st=st+i

            ans.append(st)

        ans.sort()

        return ans 

        

S=input()

ob = Solution()

ans = ob.find_permutation(S)

for i in ans:

    print(i)

 

 //SOLUTION  in c++//

#include<bits/stdc++.h>

using namespace std;


void permute(string s , string answer)

{

    if(s.length() == 0)

    {

        cout<<answer<<endl;

        return;

    }

    for(int i=0 ; i<s.length() ; i++)

    {

        char ch = s[i];

        string left_substr = s.substr(0,i);

        string right_substr = s.substr(i+1);

        string rest = left_substr + right_substr;

        permute(rest , answer+ch);

    }

 

}


int main()

{

  // Get the n elements as an input and store in arr

  string s;

  cin>>s;

  sort(s.begin(),s.end());

  string ans;

  permute(s,ans);

  return 0;

}

 

 //SOLUTION ENDS//

 

TEST-26

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

 

Input

First line contains two integers N1, N2- the lengths of the two linked lists.

Second line contains integers representing first linked list in reverse order.

Third line contains integers representing second linked list in reverse order.

 

Constraints

(1 <= N1, N2 <= 100)

0 <= value of node <= 9

It is guaranteed that input does not contain leading zeroes, except the number 0 itself.

 

Output

Print in a single line the resulting linked list.

 

Sample Input

3 3

2 4 3

7 4 5

Output

9 8 8

 

Sample Input

6 4

4 4 4 4 4 4

4 4 4 4

Output

8 8 8 8 4 4

 

 

Explanations

The idea is to reverse both input lists. The reversal is needed since the addition of two numbers is performed from right to left, but the traversal of the singly linked list is possible only from the beginning. After reversing, traverse both lists simultaneously and construct a new list with the sum of nodes from both lists. Special care needs to be taken when a sum is a 2-digit number (i.e., a carry exists) or any list runs out of elements. Note that we need to reverse the resultant list as well.

Sample 1 -> 342 + 547 = 889

Sample 2 -> 444444 + 4444 = 448888

 

#include <iostream>

#ilude<string>

using namespace std;

int main()

{

            int n,m;

 

            string l[10],l1[10];

    return 0;

}

 

 //YOUR CODE ENDS//

 

 

 //SOLUTION MENTIONED BELOW //

 

 

#include<bits/stdc++.h>

using namespace std;

 

struct LinkedListNode{

    int data;

    LinkedListNode *next;

 

    LinkedListNode(int value){

        this -> data = value;

        this -> next = NULL;

    }

};

 

LinkedListNode* append(LinkedListNode *thead, int value){

    LinkedListNode *new_node = new LinkedListNode(value);

    LinkedListNode *save_head = thead;

    if(thead == NULL){

        return new_node;

    }

    while(thead -> next != NULL) thead = thead -> next;

    thead -> next = new_node;

    return save_head;

}

 

LinkedListNode* addTwoNumbers(LinkedListNode* l1, LinkedListNode* l2) {

        LinkedListNode *t1 = l1, *t2 = l2;

        int carry = 0;

        LinkedListNode *res_head, *current = NULL;

        while(l1 || l2){

            int digit = ((l1 ? l1 -> data : 0) + (l2 ? l2 -> data : 0) + carry) % 10;

            carry = ((l1 ? l1 -> data : 0) + (l2 ? l2 -> data : 0) + carry) / 10;

            LinkedListNode* newnode = new LinkedListNode(digit);

            if(!current){

                res_head = newnode;

                current = res_head;

            }else{

                current -> next = newnode;

                current = current -> next;

                current -> next = NULL;

            }

            if(l1) l1 = l1 -> next;

            if(l2) l2 = l2 -> next;

        }

        if(carry) {

            LinkedListNode* last = new LinkedListNode(carry);

            current -> next = last;

            current -> next -> next = NULL;

        }

        return res_head;

}

 

void print_list(LinkedListNode* thead){

    while(thead != NULL){

        cout << thead -> data << " ";

        thead = thead -> next;

    }

    cout << endl;

}

 

int main(){

    LinkedListNode *head1 = NULL, *head2 = NULL;

    int n1, n2;

    cin >> n1 >> n2;

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

        int x;

        cin >> x;

        head1 = append(head1, x);

    }

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

        int x;

        cin >> x;

        head2 = append(head2, x);

    }

    LinkedListNode *res_head = addTwoNumbers(head1, head2);

    print_list(res_head);

    return 0;

}

 

 

No comments:

Post a Comment