What algorithm can be used here

This is an interview question, not a homework assignment.

Friends

N play a game. Each of them has a list of numbers in front of them.

Each of N friends selects a number from his list and informs the game administrator about it. Then the game administrator sorts the reported numbers and screams the largest number of Kth.

I need to count all the possible numbers that the game administrator can scream.

For example, if N = 3 and K = 3, and the lists for three friends are 2 5 3 , 8 1 6 , 7 4 9 . The output signal is 6, because the possible values ​​are 4 5 6 7 8 9 .

Can anyone suggest a decent algorithm for this problem? I do this to create all possible permutations with one number from each list, then sort the resulting one and print the kth largest. But it takes too much time.

+2
source share
2 answers

To find out if a number is present as a result or not, you need to know each other's list if the numbers are above, as well as the numbers below. A list where there are both numbers above and below is not a problem, since you can choose a number in them at your discretion. The problem is with lists where there are only numbers above or only numbers below. The first should be no more than NK, and the second no more than K. If this is not the case, your number cannot be selected. If so, you can always select numbers from lists where there are both numbers above and below so that your number is selected.

This can be checked in linear time, or even better if your first to sort your lists, which gives the overall complexity of O (n.log (n)), where n is the number of numbers in total. Without sorting, you got complexity nΒ².

In your example with lists:

 {2 5 3}, {8 1 6}, {7 4 9} 

They say that we are looking for the 2-greatest number. For each number, we ask if it can be shouted by the administrator. For each of them, we look to see if the other list has both numbers below and numbers above. Let's look further at some of them.

  • For 5: in both lists there are numbers above and below. So "5" can be called by the administrator.

  • For "2": in the second list there are numbers above and below, so I can freely choose the number indicated above or below in this list. But in the third list there are only numbers, so the selected number in this list will always be greater. Since I can freely choose the number lower in the second list, thereby making my β€œ2” the second highest number.

  • For "1": the second list contains only numbers, so "1" will always be the smallest element.

  • For "9": it's the other way around, it's always the biggest.

+6
source

take the smallest number from each set. find K-th is the biggest of them. This is the smallest number that is found as a result. Similarly, find the highest number as a result. Prove that the result is each number between them.

+6
source

Source: https://habr.com/ru/post/1494084/


All Articles