Skip to content

Commit

Permalink
Find top 3 and bottom 2 values from the list in O(n)
Browse files Browse the repository at this point in the history
  • Loading branch information
harishvc committed Jan 9, 2016
1 parent bd5cf63 commit a7d8a23
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Expand Up @@ -52,7 +52,8 @@ Collection of interesting questions and solutions that involve data structures,
9. [Write an "echo" program](https://github.com/harishvc/challenges/blob/master/cmd-line-echo.py)
10. [Given a list of size n, find the majority element](https://github.com/harishvc/challenges/blob/master/majority-value.py)
11. [Find min value of two unsorted lists](https://github.com/harishvc/challenges/blob/master/min-value-two-unsorted-lists.py) :bulb: :thumbsup:
12. [Given a string where each character can be [0-9] or [+-*] find the result](https://github.com/harishvc/challenges/blob/master/stack-calculator.py) :thumbsup:
12. [Given a string where each character can be [0-9] or [+-*] find the result](https://github.com/harishvc/challenges/blob/master/stack-calculator.py) :thumbsup:
13. [Find top 3 and bottom 2 values from the list in O(n)](https://github.com/harishvc/challenges/blob/master/find-top-3-bottom-3-values-in-a-list.py) :thumbsup:

### Brain Teasers (Moderate)
1. [Check if a given number is prime](https://github.com/harishvc/challenges/blob/master/prime.py)
Expand Down
67 changes: 67 additions & 0 deletions find-top-3-bottom-3-values-in-a-list.py
@@ -0,0 +1,67 @@
'''
Question: Find top 3 and bottom 2 values from the list in O(n)
'''


input = [20,5,6,100,3]

t1,t2,t3,it1,it2,it3,b1,b2,ib1,ib2 = None,None,None,None,None,None,None,None,None,None
for i,x in enumerate(input):
############
#BOTTOM 1,2
if(b2 is None):
b2 = x
ib2 = i
#smallest
elif(x < b2 and b1 is None):
#shuffle
ib1 = i
b1 = x
#new smallest
elif(x < b1):
ib2 = ib1
b2 = b1
ib1 = i
b1 = x
#next smallest
elif(x > b1 and x < b2):
b2 = x
ib2 = i
#########
#TOP 1,2,3
#Scenario 1: t3 is None
if(t3 is None):
t3 = x
it3 = i
#Scenario 2: x > t3
#shuffle back
elif(x > t3):
it1 = it2
t1 = t2
it2 = it3
t2 = t3
it3 = i
t3 = x
#Scenario 3: x < t3
#check t2 and t1
elif (x < t3):
#t2?
if (t2 is None):
t2 = x
it2 = i
#shuffle back
elif(x > t2):
it1 = it2
t1 = t2
it2 = i
t2 = x
elif(x < t2 and t1 is None):
t3 = x
it3 = i
elif(x > t1):
it1 = i
t1 = x

print(input)
print("Top 3 values >>> ", t1,t2,t3 , "and their index positions =", it1,it2,it3)
print("Bottom 2 values >>> ", b1,b2, "and their index positions =", ib1,ib2)

0 comments on commit a7d8a23

Please sign in to comment.