Python interview with a LinkedIn engineer: Matching pairs

Python interview with a LinkedIn engineer: Matching pairs

interviewing.io

4 года назад

83,456 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

Matthew Walsh
Matthew Walsh - 08.09.2023 04:28

I dont quite get why he chose python and then wrote code like that.

Ответить
Patricia Patiño
Patricia Patiño - 02.06.2023 00:30

Is any way to improve this?

from itertools import combinations

def find_pairs (values , target):
if target > 1 and len(values) > 1:
comb = combinations(values, 2)
try:
print('{} and {}'.format(*next(filter(lambda x : sum(x) == target, comb)))))
except StopIteration:
print('None Found')

Ответить
xskrish
xskrish - 20.10.2022 17:32

best solution :
1. use set (because the question didnt ask for the index, else you need to use a hashmap)
2. complete it in one iteration - O(n) by checking whether the complement exists in the set then and there.
java solution:
static int[] getMatchingPairs(int[] nums, int target){
HashSet<Integer> set = new HashSet<>();
for(int num : nums){
int complement = target - num;
if(set.contains(complement)) return new int[] {complement, num};
set.add(num);
}
return new int[] {-1, -1};
}

Ответить
Starbeyond
Starbeyond - 10.06.2022 02:25

Literally just needed a extra check before the inner return to see if it's the same number

Ответить
Mike CMW8
Mike CMW8 - 06.04.2022 04:09

Rather confusing interview. We write python to literally provide micro services in numerous docker containers reading/writing to Qs/Topics/S3 buckets/Lambdas/FTP servers/RSDBs/plotting graphs and you spend this entire interview on find the sum of two numbers in a list?? This is a bash interview! If this was my interview I would fail it. If you asked me to write 1000 lines to contact a server reliably and download a terabyte of data, I am good.

Ответить
Rafael Eder
Rafael Eder - 03.02.2022 06:40

c = [14,13,6,7,8,10,1,2]

from itertools import combinations

def comb(a,target):
solution = 'No valid pairs'
comb = combinations(a,2)
for i in list(comb):
if sum(i) == target:
solution = '{0} and {1}'.format(i[0],i[1])
print(solution)

comb(c,27)

Ответить
Arjun
Arjun - 13.01.2022 20:29

Code for this question:

x=[12,14,8,6,1,2]
y=x
for i in x:
for j in y:
if i+j==3:
result=f"{i},{j}"
break
print(result)

Ответить
eeee
eeee - 07.12.2021 01:27

lol @ actually getting two sum in an interview

Ответить
Preposterous Rhinocerous
Preposterous Rhinocerous - 30.11.2021 02:32

If only real job interviews were this easy. It's always "code a solution to the cure for cancer with O(log n)

Ответить
Trey Thomas
Trey Thomas - 27.11.2021 08:04

my solution
num_list = [14, 13, 6, 7, 8, 10, 1, 2]
target = 3
num_set = []

filtered_num_list = [i for i in num_list if i <= target]

for num in filtered_num_list:
    for n in filtered_num_list[1:]:
        if num + n == target:
            if (num, n) not in num_set and (n, num) not in num_set:
                num_set.append((num, n))

Ответить
abhishek nair
abhishek nair - 02.11.2021 23:06

Just one for loop needed and I guess it'd be more efficient to exclude values > target.


def find_pair(values, target):
val_dict = {}
for val in values:
if val < target:
if val_dict.get(val) in values:
print(f"pairs found {val} {val_dict[val]}")
return 0
val_dict[val] = target - val
print("None found")
return 1

Ответить
Joshua Covington
Joshua Covington - 20.09.2021 19:18

The criticism in the comments are ridiculous. The whole purpose of this is to practice, learn, get better, and gather feedback. This is why young software developers have a hard time because of the rude personalities that's in the area. Golden rule is to treat others the way you want to be treated. Let's not act like day one geniuses and have never improved in this line of work. smh

Ответить
edwardteach2
edwardteach2 - 17.09.2021 02:50

Please change title to - Python interview with a LinkedIn engineer: Two Sum

Ответить
Darkwing Dumpling
Darkwing Dumpling - 20.08.2021 10:20

This is literally Two Sums 😱 you need to study more my friend

Ответить
Chinmay Pandey
Chinmay Pandey - 03.05.2021 03:03

ml1 = [14, 3, 6, 7, 8, 10, 1, 2]


def find_target(x, t):
v = x.copy()
for i in x:
for j in v:
if i + j == t:
return i, j, t


print(find_target(ml1, 17))

Ответить
Sagar Shah
Sagar Shah - 08.04.2021 18:45

waiting for the day when interviewers asks me such questions lol

Ответить
canberk_gurel
canberk_gurel - 05.04.2021 04:13

Typical hash map question. It can be solved with O(N) complexity.

Ответить
Emeka Augustine
Emeka Augustine - 11.03.2021 09:08

Here is my solution for this problem; No need for second loop:

def find_pair(values, target):
value_dict = {}
for value in values:
if (target - value) in value_dict:
return "{} and {}".format(target - value, value)
value_dict[value] = value
return "No Valid Pair"

Ответить
Tenzin Tselha
Tenzin Tselha - 02.03.2021 05:56

Found a simpler way to do it.
def find_pairs(values,target):
for x in values:
for e in values[1:-1]:
if x + e == target:
print(x,"and",e)
print(True)
else:
print("not valid")

x = find_pairs([14,13,6,7,8,10,1,2],3)

Ответить
Satish Sharma
Satish Sharma - 10.02.2021 14:27

arr = [14, 13, 6, 7, 8, 10, 1, 2 ]
target = 3
for i in arr:
for j in arr:
if j + i == target:
print(f'{i} and {j}')
break


This works right?

Ответить
M. H.
M. H. - 21.12.2020 17:46

Leetcode easy problems for noobs 101.

Ответить
Neal Cantin
Neal Cantin - 08.12.2020 20:44

def find_pairs(values, target):
num_list = []
for value in values:
if value < target:
num_list.append(value)
for num in num_list:
for x in num_list:
if target == num + x:
return str(num) + " and " + str(x)

Ответить
Mehdi
Mehdi - 05.11.2020 16:58

def solution(l,n):
for i in l :
if n-i in l:
return str(i) + " and " + str(n-i)
else :
return "none!"

Ответить
anime kurniawan
anime kurniawan - 19.10.2020 21:17

How about this:

def find(nums, target):
comp = { }
for num in nums:
try:
if comp[num] == num:
return [num, target - num]
except:
comp[target - num] = target - num
return []

time complexity O(log N)
worst case O(N) when no matching pairs

Ответить
mind shop
mind shop - 19.10.2020 11:36

def find_pairs(arr, target):
d = {arr[i] : False for i in range(len(arr))}
ans = []

for num in arr:
reminder = target - num
if d[num] == False and reminder in d and num and num != reminder:
ans.append(f"{num} and {reminder}")
d[num] = True
d[target - num] = True
return ans if ans else "no valid pairs."

Ответить
ABHINAV SHARMA
ABHINAV SHARMA - 18.09.2020 18:06

I am confused

How this is faster than a "nested for loop"?

""for tagert_compliment in val_dict"" --- The in operator also uses a for loop btw.

Ответить
Valery Legasov
Valery Legasov - 10.09.2020 19:52

def find_pairs(a,target):
dic = {i: target-i for i in a if target-i>=0}
for i in dic.keys():
if dic[i] in dic:
return i,dic[i]
return 'no pairs'

Ответить
aberkb
aberkb - 07.08.2020 00:58

@13.55 that excitement when 'interviewer' finally 'understands' that -2 and says "its because 0 - 2 = -2 , True is 0" :( , man please in what language True is 0 man its 1 - 3

Ответить
Yang Chun
Yang Chun - 09.07.2020 19:54

I don’t understand why he is using dict[value] - target, (@ ; @) dict[value] = True which also = 1 and 1-3= -2 that’s why it’s constant -2 in print. It’s so easy and how could this question get fucked up....

Ответить
rohamak
rohamak - 17.06.2020 14:09

can not believe he accepted using hash table, he just cut the corner, the actual answer is using sort then step through elements from start and end end to find the pair.

Ответить
N_Fan
N_Fan - 15.05.2020 22:35

dan the solution could have done much more easily, like looping through the array 2 levels and compare each some 2 values with the target, the store them in a array

Ответить
Nate Tenhundfeld
Nate Tenhundfeld - 03.05.2020 07:18

def pairs(nums, target):
for num in range(len(nums)):
if (target-nums[num]) in nums[num+1:]:
return(str(nums[num])+ " and " + str((target-nums[num])))
return("can't be done")

Ответить
CODER GUY
CODER GUY - 30.04.2020 01:58

my solution:

target_num = 9 # change target_num to whatever you want
list = [1, 10, 4, 5] # change numbers in list to whatever you want

def find_pair(temp, ind1):
ind2 = 0
for num in list:
if ind2 != ind1:
if num + temp == target_num:
print(f"#'s that add up to {target_num}: ( {temp}, {num} ) ")
return True
ind2 += 1

ind = 0
for num_ in list:
if find_pair(num_, ind) == True:
break
elif ind == len(list)-1:
print(f"No pairs add up to {target_num}");
ind += 1

Ответить
mohamed martini
mohamed martini - 25.04.2020 07:13

['{0} and {1}'.format(n, target - n) for n in values if target - n in values][0]


'Howboudat!'

Ответить
Ronnie9P
Ronnie9P - 19.04.2020 02:41

the solution he found is extremely complicated and unecessary, this can be easily done with a double for interation, and then testing the sum of the numbers: for i in values:
for j in values:
if i+j==target:
list1.append(i)
list1.append(j)
a=sorted(set(list1))
list2.append(a)
list1.clear()
then wth a litlle tupple and sets adjustment, you can easily extract the numbers, without duplicates, i don;t understand why the long complicated coding, programers need to be simple and efficient.

Ответить
Aman Chadha
Aman Chadha - 15.04.2020 20:07

how about this (nice, simple and short):
# Program to give valid pairs which add up to target

def get_pairs(nums, target):
sublist = list(filter(lambda x: x <= target, sorted(nums)))
for i in sublist:
for j in sublist:
if i + j == target:
return((i, j))

return 'No valid pairs'

nums = [14, 13, 6, 7, 8, 10, 1, 2]
target = 24
pairs = get_pairs(nums, target)
print(pairs)

Ответить
Krishna Nigalye
Krishna Nigalye - 11.04.2020 22:01

I haven't gone through the whole video but thought of this solution.

def find_pairs(values, target):
pairs = {}
for index, x in enumerate(values):
if x not in pairs:
pairs[target-x] = x
else:
return [pairs[x], x]
return 'No Valid Pairs'

- Pairs will store (target-number) as the key and number of number as the value
Rest is easy to figure out.

Ответить
ZeroTSONG
ZeroTSONG - 15.03.2020 21:14

this audio was pretty bad

Ответить
Matty H
Matty H - 11.03.2020 06:55

This interviewer needs to stop eating...

Ответить
Mykhailo Shutkov
Mykhailo Shutkov - 11.03.2020 01:06

Hi,all.
Whar about
a = [14,13,6,7,8,10,1,2]
def foo(a,v):
dct = {}
[dct.update({x:v-x}) for x in a if x<v and x*2!=v]
for i in dct.keys():
if i in dct.values(): return (i,v-i)
print(foo(a,3))

Ответить
S27
S27 - 06.03.2020 03:57

“Hello”

Ответить
F1mus
F1mus - 16.02.2020 04:46

The 2sum solution was truly horrendous. From the misspelled "complement" to using a dictionary as a set, to concatenating integers with strings, to using two loops when one would do, to returning a string that describes an exceptional situation. Sorry for the negative comment.

Ответить
Jordon Dyer
Jordon Dyer - 14.02.2020 03:12

def find_pairs(values,target):
for num,x in enumerate(values):
if x > target:
pass
else:
solution = target - x
if solution in values[num+1:]:
return str(solution) + '&' + str(x)
return ('No pairs')

Ответить
Tanner Barcelos
Tanner Barcelos - 11.02.2020 10:35

“Python is generally easy for interviews” you got that right. Lmao

Ответить
Tokla Xen
Tokla Xen - 17.01.2020 07:07

def getpairs(values, target):
for i in values:
target_diff = target - i
for j in values:
if target_diff == j:
return str(i) + " and " + str(j)
return "No valid pairs."

Ответить