Finding the kth smallest element. This time around, suppose we have data that co
ID: 3806518 • Letter: F
Question
Finding the kth smallest element. This time around, suppose we have data that consists of integer intervals [a, b] that represent the ordered sequence (a, a + 1, a + 2, . . . , b).
Suppose we know that the intervals lie in the range [0, N]. Given [a1, b1], . . . , [an, bn] and an integer k, design an efficient algorithm that outputs the kth smallest number in the union of these intervals. Describe your running time in terms of n and N.
For example, suppose we are given [5, 25], [3, 10], [8, 12] then the union of these intervals is the sequence (3, 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 12, 12, 13, 14, . . . , 25).Hence, the 10th smallest number is 8.
(Note: Do not explicitly compute the union of the intervals because it can contain an exponential number of elements compared to your input. Rather, ask yourself the following question: Given a number x, how do you efficiently determine the number of numbers in the union of the intervals that is smaller than x? How can you use the answer to this question and questions like it to determine the kth smallest element?)
Explanation / Answer
strat
step1: declare variables arr[], k
step 2: arr[] = union of given intervals
step 3: k = user input
step 4: sort arr[]
step 5: smallest kth element = arr[k-1]
stop
So what we have done here is that we have simply assigned the union to an array(arr[]) as we do not have to compute it. Then k is determined by user input. To get the kth smallest number in the array we simply sort it and pick the number in the k-1 possition as array count starts from 0.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.