Given an array of unique randomly sorted integers and a number k it is required to find the count of the unordered pairs in the array that have a difference of k . In the text file, how many unorederd pairs of numbers have a difference of 70.
Details and Assumptions
As an example in the array
[2, 8, 4, 3, 1]
with
k
=
2
is
2
....
(2,4)
and
(3,1)
.
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
Good approach!
well im new to this but i was wondering whats "unorederd pairs "? well it also says in the" text file" but it doesnt show this text file isnt text file needed to solven the equation ?
Excellent solution!
1 2 3 4 5 6 7 8 9 |
|
This is my first try solving computer science problem any suggest please :)
Well the solution is O ( n 2 ) and could be made more efficient...
Log in to reply
i didn't get what you mean , sorry this the second day learning python.
Log in to reply
I am basically talking about the run time of the algorithm, you can learn more about it here . For large amount of items your algorithm will take longer to yield an answer.
Log in to reply
@Beakal Tiliksew – Ah , it is clear now , thank you :)
Brute Force Approach: O ( n 2 )
1 2 3 4 5 6 7 8 9 10 |
|
Two Pointers Approach: O ( n )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Here's a trivial Θ ( n 2 ) solution. I am working on improving my solution.
1 2 3 4 5 6 |
|
Surprising thing is that my solution still runs in a reasonable amount of time on my machine (about 6.92 secs).
By the way, isn't the question overrated? (400 points! whoa!)
7 seconds isn't actually reasonable considering it can be solved in a tenth of a second, and i agree the problem is overrated. Surprisingly this problem solving rate is 2%
I haven't done any timings or measurements of memory use; it's worth remembering though that building actual lists and sets (rather than using generators) takes time and space too.
And eval is naughty. ;)
1 2 3 4 5 6 |
|
Python 3.4:
1 2 3 4 5 6 7 8 9 |
|
Problem Loading...
Note Loading...
Set Loading...
Here is a Θ ( n ) solution:
Put the numbers in the list in a Hash-table
Go through each number i in the list
Check if i + 7 0 is in the Hashtable and increment a counter variable if it is. We know that despite collisions this takes O ( 1 ) via amortized analysis.
Below is a python implementation via a
set
object which is a hash-table.