Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

PYTHON 3 FOLLOW INSTRUCTIONS Complete the function countPairsThatSumToK() to take in an array and a number K, and return the number of pairs in the

PYTHON 3

FOLLOW INSTRUCTIONS

Complete the function countPairsThatSumToK() to take in an array and a number K, and return the number of pairs in the array that add up to K.

You must do this in O(n) :) no points if you do a nested loop or anything that has a complexity of O(n^2) (i.e. cannot use the in operator on an array inside a loop because the in operator for arrays takes O(n)).

Hint: use a data structure that allows O(1) lookup to store all the numbers from the array, and then loop over the array to see if for each item x, you can find another number (K-x) that helps produce a sum of K.

image text in transcribed

CODE:

def countPairsThatSumToK(array, K):

print(countPairsThatSumToK([1, 2, 3, 4, 6], 6)) # should print 1 print(countPairsThatSumToK([1, 2, 3, 4, 5], 5)) # should print 2

1 def countPairsThatSumTokCarray, K): 2 3 print(countPairsThatSumT0K([1, 2, 3, 4, 6], 6)) # should print 1 4 print(countPairsThatSumToKCC1, 2, 3, 4, 5], 5)) # should print 2 Problem Complete the function countPairsThatsumToK() to take in an array and a number K, and return the number of pairs in the array that add up to K. You must do this in O(n):) no points if you do a nested loop or anything that has a complexity of O(nA2) (i.e. cannot use the in operator on an array inside a loop because the in operator for arrays takes O(n) Hint: use a data structure that allows O(1) lookup to store all the numbers from the array, and then loop over the array to see if for each item x, you can find another number (K-x) that helps produce a sum of K

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Finance The Role Of Data Analytics In Manda Due Diligence

Authors: Ps Publishing

1st Edition

B0CR6SKTQG, 979-8873324675

More Books

Students also viewed these Databases questions