Samsung Prism - 2021 Interview Question with Solution
1. Given two binary strings, find and return the sum of those two numbers represented by those strings
Ex. num1 = 1001, num2 = 11
Answer to be returned = 1100 (=9(1001) + 3(11) )
Program
def sumofStrings(num1,num2):
num1 = "0" + num1
num2 = "0" + num2
l1 = len(num1)
l2 = len(num2)
add = ""
c = 0
if l2 > l1:
num1, num2 = num2, num1
l1, l2 = l2, l1
i = l1 - 1
j = l2 - 1
while i >= 0:
if j >= 0:
a = int(num1[i]) + int(num2[j]) + c
else:
a = int(num1[i]) + c
if a == 0:
c = 0
add = "0" + add
elif a == 1:
c = 0
add = "1" + add
elif a == 2:
c = 1
add = "0" + add
elif a == 3:
c = 1
add = "1" + add
i -= 1
j -= 1
idx = add.index("1")
return add[idx:]
sumofStrings('1001','11')
Output
1100
2.Given root of a tree and a key. Find the sum of cousin nodes at that level
Program
def findCousinSum( root, key):
if (root == None):
return -1
if (root.data == key):
return -1
currSum = 0
size = 0
q = []
q.append(root)
found = False
while (len(q)):
if (found == True):
return currSum
size = len(q)
currSum = 0
while (size):
root = q[0]
q.pop(0)
if ((root.left and root.left.data == key) or (root.right and root.right.data == key)) :
found = True
else:
if (root.left):
currSum += root.left.data
q.append(root.left)
if (root.right) :
currSum += root.right.data
q.append(root.right)
size -= 1
return -1
PS: This Question was Asked By Samsung Prism Internship - 2021
Tags:
Interview