Koolaidrain

basic interview question

Jan 19th, 2020 (edited)
420
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. # QUESTION: Given a list of size N and an integer k, find out
  2. # whether there are any two numbers in the list that add up to k.
  3.  
  4.  
  5. l = [1, 2, 3, 4, 5]
  6.  
  7. def f1(x, k):
  8. # O(n^2), brute force method
  9. for i in range(len(x)):
  10. for j in range(i+1, len(x)):
  11. if x[i] + x[j] == k:
  12. return True
  13. return False
  14.  
  15. print("f1")
  16. print(f1(l, 8))
  17. print(f1(l, 9))
  18. print(f1(l, 10))
  19.  
  20.  
  21. from bisect import bisect_left as bl
  22. def f2(x, k):
  23. # O(n * log(n)), binary search method
  24. for i in range(len(x)):
  25. b = k - x[i]
  26. j = bl(x, b)
  27. if (
  28. j in range(len(x))
  29. and i != j
  30. and x[i] + x[j] == k
  31. ):
  32. return True
  33. return False
  34.  
  35.  
  36. print("f2")
  37. print(f2(l, 8))
  38. print(f2(l, 9))
  39. print(f2(l, 10))
  40.  
  41.  
  42. def f3(x, k):
  43. # O(n), dictionary method
  44. d = {}
  45. for index in range(len(x)):
  46. value = x[index]
  47. d[value] = index
  48. for i in range(len(x)):
  49. c = k - x[i]
  50. if c in d and i != d[c]:
  51. return True
  52. return False
  53.  
  54.  
  55. print("f3")
  56. print(f3(l, 8))
  57. print(f3(l, 9))
  58. print(f3(l, 10))
Add Comment
Please, Sign In to add comment