0

The question is just like normal counting inversion question, but instead of a list of single numbers, now the input is a list of (x,y) pair.

For a list of pairs [(x1,y1),(x2,y2),(x3,y3),...,(xn,yn)], a pair (i,j) is a inversion iff i < j and xi>xj, yi>yj. Is it possible to write the algorithm in O(nlognlogn)? I tried several ways but during the merge step, each element from the right half of list has to compare with all elements in the left one, resulting in a time complexity of n square.

YS.An
  • 1
  • 2
  • If it is the same question but with only pairs of ```int``` instead of ```int```, why would the standard algo fail? – Abhinav Mathur Oct 18 '20 at 14:37
  • @Abhinav Mathur The standard algorithm works but with a cimplexity of N square. B/c for each merge&count step, you have to compare a (xj,yj) from the right part with all (xi,yi) from the left part. But I want to have a solution with a complexity of O(nlonlogn) – YS.An Oct 19 '20 at 03:27

1 Answers1

0

Split the list into two halves, left and right based on the x coordinate. Then, compare the lowest point of the two halves (based on their y coordinate). There are two cases:

  1. The left point is lower than the right point, then the left point has xi<xj and yi<yj for all the points on its right.
  2. The right point is lower than left, so the yi>yj condition hold true for any point to its left.
    After updating you answer according to these 2 cases, you can remove one of these two points and continue working on the remaining sorted lists (by recursively solving for left and right as well). This should work in O(nlog^2n)
Abhinav Mathur
  • 7,791
  • 3
  • 10
  • 24
  • Abhinav, thanks for the reply! Just one quick problem. When you split the origin list into two halves, i.e. left and right, based on x values, this would mess up the ordering in the origin list right? And thus when you campared left point(xi) with right point(xj), there is no guarantee that i < j b/c now i,j are from a sorted list instead of origin list. – YS.An Oct 19 '20 at 07:56
  • In the question, you haven't mentioned anything about the ordering on ```(i,j)``` – Abhinav Mathur Oct 19 '20 at 07:58
  • Sry, my bad :( I'll update the description. The requirement is the same as standard counting inversion. index(i,j) is called a inversion iff ixj,yi>yj. – YS.An Oct 19 '20 at 08:19
  • Where is this question posted? I'm pretty sure the question wouldn't ask for the ```i – Abhinav Mathur Oct 19 '20 at 08:34
  • It's a bonus question from a CS homework. But maybe it can use the knowledge of `half-inverted`, which is from previous part of the same question list. The `half-inverted pair` is defined as: `With a fixed constant y0 a pair (i,j) is called half-inverted if i < j, xi > xj, and yi >= y0 > yj` – YS.An Oct 19 '20 at 08:52
  • Any constraints on the values of ```xi``` or ```yi```? – Abhinav Mathur Oct 19 '20 at 10:28
  • Nope. As long as they are from the list. – YS.An Oct 19 '20 at 10:31