Question

Given an integer x and a list of integers, we have an algorithm to determine whether...

Given an integer x and a list of integers, we have an algorithm to determine whether two of the numbers add up to x. How can using hash tables improve the performance of your algorithm? (Give an overview of the idea in ~ 100 – 150 words).

0 0
Add a comment Improve this question Transcribed image text
Answer #1

We can store each element each element ina Hash Table. Now, we know that the time taken to search an element in the Hash Table is

O(1)

So, now we just have to traverse the array arr. So, for the i th element, we need to find the value of

x - arr[i]

in the Hash Table. If the element is found, then such pair exists, other wise traverse the remaining elements in the array and check again for the presence of

x - arr[i]

If we have traversed the ectire array and no such pair is found, then no such pair exists.

This method is better because in this case, we don't need the array to be sorted. As the best sorting algorithm on average takes

O(nlog_2n)

time. So, this time is not applicable in the case of Hashtable. We just store each element in HashTable in one traversal. In the other tarversal, we just check for the presence of

x - arr[i]

But, in the x and y type method, the array needs to be sorted.

So,

Time Taken = O(nlog_2n) + O(n)

  • O(nlog_2n) for sorting the array
  • O(n) for traversing the array

But in the method for HashTable, the

Time Taken = O(n) + O(n)

  • O(n) for traversing the array and storing each element in HashTable.
  • O(n) for traversing the array

Hence, the HashTable approach is better.

Add a comment
Know the answer?
Add Answer to:
Given an integer x and a list of integers, we have an algorithm to determine whether...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT