0

So, I am currently learning about closest pair algorithms and found this problem in a text book: Assume you have a sorrted Array of length n that contains one Dimensional points (integers) and are coloured. Now you want to find the closest pair of two points of different colours (either red or blue). How would you do that in O(n)? Since the closest pair of points problem is usually using a divide and conquer algorithm I was wondering whether someone has an idea on how to solve this?

I found a solution using two pointers, but no d&C solution.

Chris c
  • 3
  • 2
  • I think you've left out some important information. There doesn't seem to be an O(n) solution for the problem as stated. I think the fastest solutions would start with an O(n log n) sort. – Matt Timmermans Jan 08 '23 at 16:48
  • 1
    You can divide and conquer pretty much like the 2d case (the closest points lie in one half, or the other, or are one of 2 possibilities (largest black from left, smallest white from right) or (largest white from left, smallest black from right)). It's O(n log n), but more complicated and almost certainly slower than just sorting. – Paul Hankin Jan 08 '23 at 16:50
  • @PaulHankin Indeed I forgot to say that the array is already sorted in ascending order – Chris c Jan 08 '23 at 17:00
  • How many colours there may be? n, 2, ...? – Damien Jan 08 '23 at 19:39
  • @Damien 2 red or blue – Chris c Jan 08 '23 at 19:56
  • divide-and-conquer is just not a good approach for this problem. – Matt Timmermans Jan 08 '23 at 21:27

1 Answers1

1

You mentioned in a comment that there are only two colours, red and blue.

If we could use a divide-and-conquer approach, it would give a O(logn) solution. I don't think it is possible. However, there is a rather simple O(n) solution. We just have to memorize the value/index of last blue and red samples.

It the last read element is blue (resp. red), we calculate its distance from the last red (resp. blue) element. We then compare the result with the previous minimum distance.

Note: if the number of colours were higher, there is still a simple O(n) approach by using a stack. I originally prepared such a solution, before knowing there are only two colours.

Damien
  • 4,809
  • 4
  • 15
  • 20
  • Thanks! that was also the solution that I found, however since the previous chapter in the book was about the d&c solution of closest pair of points I was unsure whether there might not actually be a logn solution. – Chris c Jan 08 '23 at 20:27
  • In my opinion, we are obliged to examine all elements, to be sure to get the min distance. Therefore, O(n) is the best asymptotic performance. – Damien Jan 08 '23 at 20:30