Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the number of unordered pair in an array

I ran into an interesting algorithm problem:

Given an array of integer, find the number of un-ordered pairs in that array, say given {1, 3, 2}, the answer is 1 because {3, 2} is un-ordered, and for array {3, 2, 1}, the answer is 3 because {3, 2}, {3, 1}, {2, 1}.

Obviously, this can be solved by brute force with O(n^2) running time, or permute all possible pairs then eliminate those invalid pairs.

My question is does any body have any better solution and how would you do it because it seems like a dynamic programming problem. A snippet of code would be helpful

like image 554
Mighty_L Avatar asked Nov 02 '14 17:11

Mighty_L


People also ask

What is unordered pairs in array?

In mathematics, an unordered pair or pair set is a set of the form {a, b}, i.e. a set having two elements a and b with no particular relation between them, where {a, b} = {b, a}. In contrast, an ordered pair (a, b) has a as its first element and b as its second element, which means (a, b) ≠ (b, a).

How do you find the number of pairs?

= n(n-1) / 2 which is our formula for the number of pairs needed in at least n statements.

How do you find a pair in an array?

In order to find all the possible pairs from the array, we need to traverse the array and select the first element of the pair. Then we need to pair this element with all the elements in the array from index 0 to N-1. Below is the step by step approach: Traverse the array and select an element in each traversal.

How do you find the number of pairs in an array in C++?

Count pairs in an array that hold i+j= arr[i]+arr[j] Given an array of integers arr[], the task is to count all the pairs (arr[i], arr[j]) such that i + j = arr[i] + arr[j] for all 0 ≤ i < j < n. Note: Pairs (x, y) and (y, x) are considered a single pair.


1 Answers

It is possible to solve this problem in O(n log n) time using a balanced binary search tree. Here is a pseudo-code of this algorithm:

tree = an empty balanced binary search tree
answer = 0
for each element in the array:
     answer += number of the elements in the tree greater then this element
     add this element to the tree
like image 126
kraskevich Avatar answered Oct 05 '22 09:10

kraskevich