SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Anany Levitin
Chapter:
Introduction
Exercise:
1.1 Exercise
Question:5 | ISBN:9780132316811 | Edition: 3

Question

Design an algorithm to find all the common elements in two sorted lists of numbers. For example, for the lists 2, 5, 5, 5 and 2, 2, 3, 5, 5, 7, the output should be 2, 5, 5.What is the maximum number of comparisons your algorithm makes if the lengths of the two given lists are m and n, respectively?

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

To find all the common elements in two sorted lists of numbers, you can use a simple algorithm that compares the elements of the two lists. Here's the algorithm:

  1. Initialize two pointers, one for each list, starting at the first element.

  2. While both pointers are within the bounds of their respective lists:

    • If the elements pointed to by both pointers are equal, add the element to the common elements list and move both pointers to the next element.
    • If the element in the first list is smaller, move the first pointer to the next element.
    • If the element in the second list is smaller, move the second pointer to the next element.
  3. Return the common elements list.

The algorithm works because the lists are sorted. The maximum number of comparisons made by this algorithm occurs when both lists are fully traversed. In the worst-case scenario, each element in one list must be compared to every element in the other list.

 

Therefore, the maximum number of comparisons is m * n, where m is the length of the first list and n is the length of the second list.

0 0

Discussions

Post the discussion to improve the above solution.