Count Number of Triples in an array that are collinear

后端 未结 6 774
梦谈多话
梦谈多话 2021-02-01 09:31

I was asked this Interview Question (C++,algos)and had no idea how to solve it.

Given an array say Arr[N] containing Cartesian coordinates of N distinct points count the

6条回答
  •  北海茫月
    2021-02-01 10:02

    I have this solution tell if there is a better one,

    Sort all the points according to the slope they make with the x axis or any other axis you want ( O(n* logn) ). Now all you have to do if go through the sorted list and find points which have same slope either inpositive or negative direction( this can be done in linear time i.e. O(n) ) . Lets say you get m such points for one case then increment the answer by C(m,3)..

    Total time depends on how good you implement C(m,3)

    But asymptotically O(N logN)

    Edit: After seeing icCube's comment i realize that we cannot take any axis..so for the above defined algo taking the slope calculating point as one of the n points ( thus n times ) should be my best guess. But it makes the algorithm N*N*Log(N)

提交回复
热议问题