130k views
5 votes
Given a collection of n nuts, and a collection of n bolts, each arranged in an increasing order of size, give an O(n) time algorithm to check if there is a nut and a bolt that have the same size. You can assume that the sizes of the nuts and bolts are stored in the arrays NUTS[1::n] and BOLTS[1::n], respectively, where NUTS[1] < < NUTS[n] and BOLTS[1] < < BOLTS[n]. Note that you only need to report whether or not a match exists; you do not need to report all matches.

User Tai Dao
by
4.5k points

1 Answer

4 votes

Answer:

See explaination for the program code

Step-by-step explanation:

Keep two iterators, i (for nuts array) and j (for bolts array).

while(i < n and j < n) {

if nuts[i] == bolts[j] {

We have a case where sizes match, output/return

}

else if nuts[i] < bolts[j] {

this means that size of nut is smaller than that of bolt and we should go to the next bigger nut, i.e., i+=1

}

else {

this means that size of bolt is smaller than that of nut and we should go to the next bigger bolt, i.e., j+=1

}

}

Since we go to each index in both the array only once, the algorithm take O(n) time.