TCS Ninja Numerical AbilityQuestions 

 

Q1. The LCM and HCF of the three numbers 48, 144 and p are 720 and 24 respectively, find the least value of p.

A.   192

B.   120

C.  360

D.  180

Answer: B

 

Q2. Simplify and find the value

0.0217 x 3.18

0.0053 x 15.5 x 0.7

A.   1.2

B.   0.12

C.  12

D.  0.012

Answer: A

 

Q3. What value should come in the place of question mark (?) in the following equation?

8 / [2 x 2 - {14 + (2 / 4 x 4) - 13}] = ¾ + ?

A.   2

B.   1/4

C.  29/4

D.  5/16

Answer: C

 

Q4. Simplify and find the value,

216 x 216 + 216 x 194 + 194 x 194

 

216 x 216 x 216 - 194 x 194 x 194

A.   1/11

B.   2/11

C.  1/22

D.  1/33

Answer: C

 

Q5. Boy scored 90 marks in his mid-term exam and 105 in his end-term exam. If the maximum marks in both the examinations are 150, then find the increase in his marks in percentage points. A. 10%

B.    15%

C.   14.28%

D.   16.66%

Answer: A

Q6. A shopkeeper marks the sale price of all items in his shop at 20% above the cost price of those items. However, he offers a discount of 15% on the sale price of these items to his customers. Calculate the profit earned by him, in percentage.

A.   5%

B.   2%

C.  10%

D.  2.5%

Answer: B

 

Q7. Plant A of a factory, during audit 6% of parts got rejected from the total production. In Plant B, the same number of parts were rejected with 96 units of parts rejected less than Plant A. What was the number of parts produced by each factory?

A.   4800

B.   10000

C.   9600

D.   7200 Answer: A

 

Q7. Amounts at the end of 2 yrs and 3 yrs are Rs. 1170 and Rs. 1305 on a certain sum, at a certain rate of simple interest. Find the rate of interest. A. 12% p.a.

B.   9% p.a.

C.  15% p.a.

D.  18% p.a.

Answer: C

 

Q8.

If the number of males and females in town P are equal and the number of females in town Q is 50% more than the number of males in the town Q, then what is the difference between the average age of males and females together in town P and the average age of males and females together in town Q? A. 6 years

B.    8 years

C.   5 years

D.   9 years

Answer: A

Q9. In a certain amount, compound interest at the rate of 12.5% per annum for the fifth year 2048. If the interest is compounded annually. What is the compound interest for the 8th year? A. $ 2592

B.   $ 2304

C.   $ 2916

D.   $ 3280

Answer: C

 

Q10. R and company has two directors, X and Y who have invested Rs. 1,25,000 and 1,00,000 respectively. X is the working partner and hence takes 5% of the profit as his salary. Find X’s share of the profit, if their annual profit is Rs. 72,000.

A.   40,000

B.   32,000

C.   38,000 D. 42,000 Answer: C

 

Q10. In how many given years is the income of P in a year, more than then the average of the income of P and Q in the same year?

A.  4

B.  2

C.  3

D.  5

Answer: A

 

Q11. Two numbers having their LCM 480 are in a ratio 3 : 4. What will be the smaller number of this pair?

A.   180

B.   120

C.  160

D.  240

Answer: B

 

Q12. Quantity of wine in a mixture (wine + water + soda) is 24 ml more than water and 40 ml less than soda. When 20% mixture is replaced by water, the total quantity of water in the mixture becomes 208 ml. What is the initial quantity of wine in the mixture?

A.  180 ml

B.  120 ml

C.  160 ml

D.  140 ml

Answer: C

 

Q13. Two taps A and B fill an empty tank in 40 mins and 60 mins respectively. If both the taps are opened at 5 am, then at what time A be closed so that the tank is filled in 36 mins? A. 5.22 am

B.  5.12 am

C.  5.16 am

D.  5.05 am

Answer: C

 

Q14. 6 men together can complete a one-third of work in 12 days. Four women together can complete half of the same work in 27 days and nine boys together can complete three-fourth of the same work in 54 days. In how many days can three men, 2 women and 3 boys together complete the work?

A.  30 days

B.  36 days

C.  24 days

D.  45 days

Answer: B  

Q15. Sindhu, Madhavi and Jayanthi are participating in a 3 x 900 metres relay race. Sindhu covered her distance in 3 minutes. Madhavi covered her distance in 4 minutes. How much time should Jayanathi take to finish the race to maintain the team’s average speed at 4 m/s?

A.  4 minutes

B.  5.25 minutes

C.  4.25 minutes

D.  3.75 minutes

Answer: C

 

 

Q16. A box contains a total of 45 coins of one rupee, five rupees and two rupees. The total value of all the coins in the box is Rs. 91. The number of one rupee coin is one more than the total number of 5 rupees and two rupees coins. What is the number of five rupees coins in the box? A. 12

B.  8

C.  6

D.  10

Answer: B  

Q17. Akshat’s walking speed is 5 km/h. The bus stop is 1 kilometre away from his house. Akshat walks to the bus stop and then takes a bus to school. The speed of the bus is 40 Km/h. Akshat’s school is 10 Kilometers away from the bus stop. How much time will Akshat take to reach his school form his house, if he boards a bus as soon as he reaches the bus stop?

A.  20 minutes

B.  34 minutes

C.  27 minutes

D.  30 minutes

Answer: C  

Q18. A park is square in shape with its perimeter four times the perimeter of a rectangle having length 15 metres and breadth 10 metres. There is a semi-circular lawn inside the park that has a diameter equal to the side of the square. Calculate the perimeter of this lawn.(Take n = 3.14).

A.  140 metres

B.  50 metres

C.  128.5 metres

D.  125.5 metres

Answer: C

 

Q19. A magician wants to hide his magical rod inside a cubical box whose total surface area is 3042 cm2.

What can be the maximum length of the rod?

A.  37 cm

B.  42 cm

C.  33 cm

D.  39 cm

Answer: D

 

Q20. The average of 13 consecutive natural numbers in x. If the seventh number is 22, find x.

A.  20

B.  22

C.  28

D.  14

Answer: B

 

Q21. The standard deviation of prime numbers between 60 and 80 is 6.72. If each observation is multiplied by the median of the numbers, then find the difference of standard deviations of the obtained observations and median of the numbers.

A.    484.68

B.    412.36

C.   406.12

D.   477.12

Answer: D

TCS Ninja Verbal Ability Questions                                                                                 

 

Q1. The part of the sentence below may contain an error. Identify the part. If there is no error, choose ‘No error’.

World Health Organisation must intensify their efforts to vaccinate people in African countries.

 

A.  World Health Organisation must

B.  people in African countries.

C.  No error

D.  intensify their efforts to vaccinate Answer: D

 

Q2. The part of the sentence below may contain an error. Identify the part. If there is no error, choose ‘No error’.

A paramedic is expected to be highly skilled into dealing with emergency patients.

 

A.  highly skilled into dealing with

B.  No error

C.  emergency patients

D.  A paramedic is expected to be Answer: A

 

Q3. The part of the sentence below may contain an error. Identify the part. If there is no error, choose ‘No error’.

The rise in the price of oil and an increase in demand has forced some farmers to harvest oil crops for biofuels.

 

A.  farmers to produce oil crops for biofuels.

B.  No error

C.  in demand has forced some

D.  The rise in the price of oil and an increase Answer: C

 

Q4. Select the most appropriate option to fill in the blank.

 

I have a lot of work to do. I can’t leave the office                         one hour.

A.  by

B.  until

C.  for

D.  since

Answer: C

 

Q5. Read the following passage and fill in the blanks by selecting the more appropriate options.

 

By 2025, marketing campaigns 1 relied on Artificial Intelligence to enhance customer experience. Companies will be communicating their  2 only through personalised and curated content.

Blank 1: A. will B. will have   C. would   D. wil being

Blank 2: A. uniqueness B. marketing C. future D. products

 

A.   1-B, 2-A

B.   1-B, 2-B

C.  1-D, 2-B

D.  1-A, 2-C

Answer: A

 

Q6. Read the following passage and fill in the blanks by selecting the more appropriate options.

 

The main cause of teachers leaving the workforce is not tough and rigid work contract in schools, but   is poor working condition meagre salaries.

 

Blank 1: A. rather          B. however       C. so D. then

Blank 2: A. aroused        B. worsened C. aided            D. eased

 

A.  1-A and 2-B

B.  1-B and 2-B

C.  1-A and 2-D

D.  1-D and 2-C

Answer: 1-A 2-C (Not in option)

 

Q7. Select the most appropriate option to fill in the blank.

 

Almost all colonial buildings have been so altered and developed that their structure is no longer

             .

A.  external, necessary

B.  original, recognisable

C.  main, found

D.  Internal, attractive

Answer: B

 

 

Q8. For the four sentence (S1-S4) paragraph below, sentences S1 and S4 are given. From the options P, Q and R choose the appropriate sentences for S2 and S3 respectively.

 

S1. Some 200 km from Leh are the villages of Dha, Hanu, Garkone and Darchik on both sides of the Indus river, inhabited by the Buddhist Dard Tribes.

S2. S3.

S4. He added people of this region are culturally and linguistically different from those in other parts of Ladakh.

 

P.  The villages are together called the “Aryan valley”

Q. “The word ‘Dard’ is derived from the Sanskrit word, ‘Daradas’, which means people who live on hillsides”, said Virendra Bangroo, assistant professor at Indira Gandhi National Centre for the Arts (IGNCA), who has extensively researched on their lives.

R. There is also a line of thought that the “Aryans of Ladakh” might have descended from soldiers in Alexander’s army who had come to the region over 2,000 years ago.

 

A.  RP

B.  QP

C.  PR

D.  PQ

Answer: D  

Q9. For the four sentence (S1-S4) paragraph below, sentences S1 and S4 are given. From the options P, Q and R choose the appropriate sentences for S2 and S3 respectively.

 

S1. When employees are constantly working for a long time, they start getting influenced by others’ moods and vibes.

S2. S3.

S4. But this emotional transfer also happens through digital communication.

 

P.   This phenomenon is known as emotional contagion.

Q.  Positive emotions lead to higher productivity, creativity, and job performance.

R.  Emotional contagion is most pronounced when employees are together physically.

A.  PQ

B.  PR

C.  QP

D.  RP

Answer: B

 

Q10. You are going to read a text. Parts of two sentences are missing from the text. Choose from the list (A-C) the most appropriate part to complete the sentence for each gap (1-2) in the text. There is one extra part that you do not need to use.

 

Those who are concerned about society may be troubled by the idea of overdependence on technology

          (1)          We have made technology our primary religion and culture. (2)             

 

A.        It has started to overtake us because it has crippled our ability to keep a track of events around us.

B.        Our new religion and culture is making us more confident and productive.

C.        Our deviation from our roots affects our ability to trust each other.  

A.  (1) B and (2) C

B.  (1) C and (2) A

C.  (1) A and (2) B

D.  (1) A and (2) C

Answer: D

 

 

Q11. Which of the following sentences uses formal language?

A.  Numerous research methods were considered for the study.

B.  It was raining cats and dogs.

C.  She uses loads of examples in the class.

D.  The improvements can’t be introduced due to funding restrictions. Answer: A

 

Q12. The following sentence pair can be combined into one better sentence. Choose the option that combines the two sentences best.

 

I completed the assignment. I submitted the assignment.

 

A.  I completed but submitted the assignment

B.  I completed the assignment and submitted it

C.  I completed the assignment, however, I submitted the assignment

D.  Although I completed the assignment, I submitted the assignment Answer: B

 

Q13. You are going to read a text. Partes of two sentences are missing from the text. Choose from the list (A-C) the most appropriate part to complete the sentence for each gap (1-2) in the text. There is one extra part that you do not need to use.

 

In order to conduct clinical trials of medical treatments, scientists gather a huge amount of information of their patients. 1 Some researchers argue that medical research can be massively improved by a shift toward artificial Intelligence. 2 .

 

A.  This can result in more efficient and less complicated clinical trials of medical treatments.

B.  This can pave the way for more innovative and cost-efficient treatment.

C.  This practice increases the costs of collecting, storing and analysing data.

 

A.   1-A, 2-C

B.   1-B, 2-A

C.  1-B, 2-C

D.  1-C, 2-A Answer: D

TCS Ninja Reasoning Ability Questions                                                                         

 

Q1. Which is the WRONG term in the following series?

mkl, imj, gqh, csf, awd, wyb, udw

 

A.  csf

B.  udw

C.  awd

D.  wyb

Answer: B

 

Q2. In each of the five pairs of letter clusters, the letters in a second term are a rearranged/transformed form of the letters in the first term in a particular pattern. In which two pairs, has the transformation been done in the same way? A. ACTOR:CROTA

B.  BENCH:CEHBN

C.  CHAIR:ARHCI

D.  DIRTY:RYITD

E.  ENJOY:JYNEO

 

A.  A and C

B.  B and D

C.  E and C

D.  B and E

Answer: D

 

Q3. Given below is a question followed by two statements, I and II each containing some information. Decide which of the statement(s) is/are sufficient to answer the question.

How many persons are sitting in the row?

Statements:

I.    Ghazi, who is 5th to the right of Anish, is 12th from the left end. Anish is 15th from the right end.

II.  Zenia is 4th to the left of Karan, who is 15th from the right end.

 

A.  Statement I alone is sufficient.

B.  Statement I alone or statement II alone is sufficient.

C.  Statement II alone is sufficient.

D.  Both the statements I and II together are not sufficient. Answer: A

 

Q4. Given below is a question followed by two statements, I and II each containing some information. Decide which of the statement(s) is/are sufficient to answer the question.

 

Six persons P to Q are sitting in a row facing north direction. Who among the following sits at extreme right end?

 

Statement I:

P sits third to the left of U. Q sits two places away from P but not adjacent to U. T sits immediate left of S.

Statement II:

There are two persons between Q and T. S sits to the immediate left of U but to the right of T. Neither S nor U is adjacent.

 

A.  If the data in statement II alone is sufficient to answer the question

B.  If the data either in statement I or statement II alone is sufficient to answer the question.

C.  If the data in statement I alone is sufficient to answer the question.

D.  If the data in both statements I and II together are not sufficient to answer the question.

 

Answer: B

 

 

Q5. In a certain code, if:

S#T means S is the father of T

S@T means S is the wife of T

S%T means S is the brother of T

S$T means S is the sister of T

S&T means S is the daughter of T

S*T means S is the son of T

 

I.           E*C

II.         H@F

III.       J*G

IV.      F%E

V.        L$K

VI.      J%I

VII.    I&E

VIII.  K*F

IX.      F*D  

Who among the following is not a male?

 

A.  J

B.  F

C.  L

D.  E

Answer: C

 

 

Q6. A, B, C, D, E, F and G are standing in a row facing north. B is to the left of D. There are two persons C and G. E is adjacent of B and C. F is to the immediate right of G.

 

Who is standing exactly in the middle?

 

A.  F

B.  E

C.  C

D.  A

Answer: C

 

Q7. Eight persons A, B, C, D, E, F, G and H are sitting around a circular table. The following is the information known about them. B is opposite E who is neither adjacent to C nor to D. H is to the right of E and D is to the right of B. C does not sit near D and H. A does not sit near H and E. Two people sit between G and D, when counted from the right of G. Who is sitting opposite G? A. F

B.  C

C.  A

D.  H

Answer: C

 

 

Q8. Six persons Vinay, Vijay, Varun, Varsha, Vinod and Vartika were seated in a row not necessarily in the same order. They were seated facing the north, Vijay was 2nd to the right of Varsha who was seated at a gap of 3 from Vartika.Vinay was 2nd to the right of Varun who was not neighbouring Vijay. Who was seated to the immediate right of Vinod?

 

A.  Varsha

B.  Vartika

C.  Varun

D.  Vijay

Answer: B

 

Q9. Mahendra is going to buy a laptop, following are the criteria of selection of the laptop given by his father. a) must be for less than Rs. 40,000

b)  must have RAM equal or more than 8GB

c)   must have Intel processor of version i3 or above

d)  If any laptop is satisfying all the above criteria except (a), he will need his dad’s permission if ir is for less than Rs. 50,000

e)  If any laptop is satisfying all the above criteria except (b), he will need his mom’s permission if it has storage of more than 512 GB.

 

Acer AT20 is a new laptop in the market costing Rs. 35,000 and having 8GB RAM. It consists of processor i5 and pre-installed windows 10.

 

Which of the following options below is CORRECT for the laptop given above?

 

A.  He needs mom’s permission to buy it

B.  He will buy the laptop

C.  He will not buy the laptop

D.  He needs dad’s permission to buy it Answer: B

 

Q10. Shekar asked his girlfriend to book a hotel in Udaipur for their trip. Following are the selection of hotel they have decided:

 

(a)  Price of hotel must be less than Rs. 5000 per night.

(b)  Couple should be allowed.

(c)   It should be within 10km from the railway station.

(d)  If a hostel satisfies all the criteria except (a) but it is providing online payment option, she will ask her friend for finalization.

(e)  If a hotel satisfies all the criteria except (c) but it provides free breakfast, she will ask Shekhar for finalisation.

 

“Hotel Disaster Inn” is offering super deluxe room at the price os Rs. 4500 per night. Its rating on Google is 4.5 and it is 12 km from railway Station. Hotel policy allows couple to check in with original ID card and pay in cash. Free breakfast, sofas, swimming pool, parking, lift and AC are mentioned in the facilities.

Which of the following options below is CORRECT for the selection of hotel above?

 

A.        It will not be finalised by her friend.

B.        She will ask Shekar for finalisation.

C.        It will be selected by her.

D.        She will ask her friend for finalization Answer: B  

Q11. Three statements are followed by three conclusions number I, II and III. Assuming the statements to be TRUE, even if they do not confirm world knowledge, decide which of the conclusion(s) possibly follows/follow from the statements.

 

Statements:

1.         Some vehicles are trucks.

2.         All aeroplanes are vehicles.

3.         No truck is car.  

Conclusions:

I.      No car is aeroplane.

II.    It is possible that some trucks are aeroplanes.

III.  Some cars are aeroplanes.

 

A.  Only II follows

B.  Only I and II follow

C.  Only II and III follow

D.  Only II and either I or III follow

 

Answer: A

Q12. Two statements are followed by two conclusions numbered I and II. You have to consider these statements to be true, even if they seem to be at variance with commonly known facts. Decide which of the given conclusions logically follows from the given statement.

 

Statements:

All paths are roads

Some roads are highway

 

Conclusions:

I.    Some highways are paths

II.  All paths being highway is a possibility

 

A.  Both conclusions I and II follow

B.  Only conclusion I follow

C.  Neither conclusion I nor II follow

D.  Only conclusion II follows

Answer: D

 

 

Q13. A statement is followed by two arguments numbered I and II. Decide which of the argument(s) is/ are strong (important and directed related to the question) and which is/ are weak (not important and not related to the central message of the question).

Statement : Should the Government of India privatise their shares of public entities?

Argument I. No, it will reduce their assets, which can help them in the difficult time.

Argument II. Yes. Mixed economies like India will be in better condition if they do so.

A.  Only argument II is strong

B.  Neither I nor II is strong

C.  Both I and II are strong

D.  Only Argument I is strong

Answer: A

 

Q14. The given question consists of six statements followed by 4 options consisting of three statements put together in a specific order. Choose the option, which indicates a valid argument that is, when the third statement is a conclusion drawn from the preceding two statements.

(a)  Some mails are falis

(b)  Bail is a fail

(c)   Some jail is mail

(d)  Fail is jail

(e)  No mail is a fail

(f)    No bail is mail

A.  b e f

B.  c b a

C.  a f b

D.  c d e

Answer: A

Q15. The ratio of the number of executive and non-executive employees working in a company is 2:5. 50% of the executives and 30% of the non-executives stay outside the company campus. 350 of the employees staying outside the campus live in their own houses with the ratio of 2:3 between executives and non- executives, while the rest live in rented houses. 60 non-executives stay in rented houses. 60% of the employees staying in rented houses travel to their workplace by two-wheelers and the rest 40% travel by the company bus. The number of executives travelling by the company bus is 15.

 

I. How many employees are working in the company?

 

A.   1080

B.   1180

C.   1320

D.   1260

Answer: D

 

II. How many non-executives travel by the company bus to their workplace?  

A.  35

B.  15

C.  40

D.  25

Answer: D

 

 

Q16. If the given figure is folded to form a cube, which symbol will come opposite to “Z”?

A.  L

B.  B

C.  R

D.  K

Answer: D

 

Q17. The ratio of the number of executive and non-executive employees working in a company is 2:5. 50% of the executives and 30% of the non-executives stay outside the company campus. 350 of the employees staying outside the campus live in their own houses with the ratio of 2:3 between executives and non- executives, while the rest live in rented houses. 60 non-executives stay in rented houses. 60% of the employees staying in rented houses travel to their workplace by two-wheelers and the rest 40% travel by the company bus. The number of executives travelling by the company bus is 15.

How many executives are staying outside?

A.   210

B.   180

C.  120

D.  140

Answer: D

TCS Ninja Programming Logic Questions                                                                     

 

Q1. What is the output of the prefix expression +, -, *, 7, 2, /, 9, 3, 1?

A.  13

B.  10

C.  11

D.  12

Answer: D

 

Q2. What is the output of the following code? Integer digit = 0; if digit print “1” else

print “digit”

 

end if A.1

B.0

 

C.digit

 

D.Nothing will print

 

Answer: C

 

Q3. What is the output of the code?

#include <stdio.h>

void f(int*p, int*m)

 

{*m=*m+3;

 

*p=*p+*m;

return;

}

 

int main ()

 

{

int i = 5, j = 6; int k=0; f(&i,&j); k=(i*j); printf(“%d”, k); return 0;

}

 

A.   134

 

B.   126

 

C.  125

 

D.  138

 

Answer: B

 

Q4. What is the output of the below code?

#include <iostream> using namespace std; int main ()

{

 

Int skip_num;

 

for (skip_num = 1; skip_num<=5; skip_num++){ if(skip_num = =2 || skip_num = =4){

continue;

 

}

 

cout<<skip_num;

 

cout<<’’

 

}

 

return 0;

}

 

A.   1 3 5

 

B.   1 3 4 5

 

C.  1 2 5

 

D.  2 4 6

 

Answer: A

 

Q5. Below is the JSON format to share the employee data.

 

{

 

“id”: “001”,

 

“Name’: “John”

“Department”: “QA”

A JSON format, designed with a collection of (key, value) and pairs in which each of the key appears at once in the collection.

Which type of data structures is most suitable to implement JSON format?

 

A.  Doubly Linked List

 

B.  AVL Tree

 

C.  Single Linked List

 

D.  Associative Array

 

Answer: B

 

Q6. Evaluation of cyclomatic complexity comes under which type of testing?

 

A.  Black Testing

 

B.  White Testing

 

C.  Stress Testing

 

D.  Gray Testing

 

Answer: B

 

Q7. What is the output of the below code?

#include <stdio.h>

Void main ()

{

Int rate = 15, piece = 10, interim, result = 0; interim = rate % piece; result + = interim / 5 printf(“%d, result);

}

A.        10

B.        2

C.        5

D.        1 Answer: D

 

Q8. What will be the output of the given program?

#include <iostream> using namespace

std; int main ()

{

 

Int sides = 3;

Int lines = 3;

If (!(sides^lines)} cout<< “Triangle”; else cout<<”Others”; return 0;

}  

Enter your answer in the box.

 

Answer: Triangle

 

Q9. Predict the output of the following code

#include<iostream> using namespace std;

 int main()

{

 int a = 3, b = 5; while(b--) a++;

 cout << a; return 0;

}

 

Answer: 8

TCS Ninja Hands-on Coding Questions                                                                         

 

Q1. Airport security officials have confiscated several items of the passenger at the security checkpoint. All the items have been dumped into a huge box(array). Each item possessed a certain amount of risk(0,1,2). Here is the risk severity of the item representing an array[] of N number of integer values. The risk here is to sort the item based on their level of risk values range from 0 to 2.

Example 1:

 

Input:

 

7 ------------- Value of N

 

[1,0,2,0,1,0,2] -> Element of arr[0] to arr[N-1], while input each element is separated by new line

 

Output:

 

0 0 0 1 1 2 2 -> Element after sorting based on the risk severity.

 

Example 2:

 

Input:

 

10 ------------ Value of N

 

[2,1,0,2,1,0,0,1,2,0] -> Element of arr[0] to arr[N-1], while input each element is separated by new line

 

Output:

 

0 0 0 0 0 1 1 1 2 2 2 -> Element after sorting based on the risk severity.

 

Constraints

 

0<N<=100

 

0<=arr[i]<=2

 

Code Solution:

#include<iostream> using namespace std; int main()

{

 

int n;

 

cin >> n;

int arr[n];

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

 {

 

cin >> arr[i];

 }

 

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

 {

 

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

 

{

 

if(arr[i] > arr[j])

 

{

 

int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;

}

 

}

 }

 

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

 {

 

cout << arr[i] << “ ”;

 

}

 

}

Q2. Given N gold wires, each wire has a length associated with it. At a time, only two adjacent small wres assembled at the end of a large wire and the cost of forming is the sum of their length. Find the minimum cost when all wires are assembled to form a single wire.

 

For Example:

 

Suppose, Arr[] = {7, 6, 8, 6, 1, 1}

{7, 6, 8, 6, 1, 1} - {7, 6, 8, 6, 2}, cost = 2

{7, 6, 8, 6, 2} - {7, 6, 8, 8}, cost = 8

{7, 6, 8, 8} - {13, 8, 8}, cost =13

{13, 8, 8} - {13, 16}, cost = 16

{13, 16} - {29}, cost = 29

2 + 8 + 13 + 16 + 29 = 68

 

Hence, the minimum cost to assemble all gold wires is : 68

 Constraints:

 

1 <= N <= 30

1<= Arr[] <= 100

 

Example 1:

 Input:

 

6            -> Value of N, represents size of Arr

7            -> Value of Arr[0], represents length of 1st wire

6          -> Value of Arr[1], represents length of 2nd wire

8          -> Value of Arr[2], represents length of 3rd wire

6          -> Value of Arr[3], represents length of 4th wire

-1        -> Value of Arr[4], represents length of 5th wire

1          -> Value of Arr[5], represents length of 6th wire

 

Output:

 

68

 Example 2:

 Input:

 

4         -> Value of N, represents size of Arr

12        -> Value of Arr[0], represents length of 1st wire

2          -> Value of Arr[1], represents length of 2nd wire

2          -> Value of Arr[2], represents length of 3rd wire

5          -> Value of Arr[3], represents length of 4th wire

 

Output:

 

34

 

Code Solution

 

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

 

struct MinHeap { unsigned size; unsigned capacity; int* harr;

};

 

 

struct MinHeap* createMinHeap(unsigned capacity)

{

struct MinHeap* minHeap = new MinHeap; minHeap->size = 0; minHeap->capacity = capacity; minHeap->harr = new int[capacity]; return minHeap;

}

 

 

void swapMinHeapNode(int* a, int* b)

{

int temp = *a; *a = *b;

*b = temp;

}

 

 

void minHeapify(struct MinHeap* minHeap, int idx)

{

int smallest = idx; int left = 2 * idx + 1; int right = 2 * idx + 2;

 

if (left < minHeap->size

&& minHeap->harr[left] < minHeap->harr[smallest]) smallest = left;

 

if (right < minHeap->size

&& minHeap->harr[right] < minHeap->harr[smallest]) smallest = right;

 if (smallest != idx) {

swapMinHeapNode(&minHeap->harr[smallest], &minHeap->harr[idx]); minHeapify(minHeap, smallest);

}

}

 

 

int isSizeOne(struct MinHeap* minHeap)

{

return (minHeap->size == 1);

}

 

 

int extractMin(struct MinHeap* minHeap)

{

int temp = minHeap->harr[0]; minHeap->harr[0] = minHeap->harr[minHeap->size - 1];

--minHeap->size; minHeapify(minHeap, 0); return temp;

}

 

 

void insertMinHeap(struct MinHeap* minHeap, int val)

{

++minHeap->size; int i = minHeap->size - 1; while (i && (val < minHeap->harr[(i - 1) / 2])) { minHeap->harr[i] = minHeap->harr[(i - 1) / 2]; i = (i - 1) / 2;

}

minHeap->harr[i] = val;

}

 

 

void buildMinHeap(struct MinHeap* minHeap)

{

int n = minHeap->size - 1;

int i; for (i = (n - 1) / 2; i >= 0; --i) minHeapify(minHeap, i);

}

 

 

struct MinHeap* createAndBuildMinHeap(

int len[], int size)

{

struct MinHeap* minHeap = createMinHeap(size);

for (int i = 0; i < size; ++i) minHeap->harr[i] = len[i];

minHeap->size = size; buildMinHeap(minHeap); return minHeap;

}

 

 

int minCost(int len[], int n)

{

int cost = 0;

 

 

struct MinHeap* minHeap = createAndBuildMinHeap(len, n);

 

 

while (!isSizeOne(minHeap)) {

 

int min = extractMin(minHeap); int sec_min = extractMin(minHeap); cost += (min + sec_min);

 

insertMinHeap(minHeap, min + sec_min);

}

 

 

return cost;

}

 

 

int main()

{ int n; cin >> n; int arr[n]; for(int i = 0; i < n; i++)

cin >> arr[i];

int size = sizeof(arr) / sizeof(arr[0]); cout << minCost(arr, size); return