Google Python Interview Question

Python Short Codes
2 min readDec 25, 2022

--

with explantion.

Q1. Find all triplets with sum as zero.

First, we define a function called find_triplets that takes a list of integers as an argument. This function will be used to find all triplets with zero sum in the given list.

def find_triplets(numbers):

Inside the function, we define a variable called triplets to store the triplets that we find. Initially, this variable is an empty list.

  triplets = []

Next, we use a loop to iterate over the elements of the list. This loop will be used to select the first element of the triplet.

  for i in range(len(numbers)):

Inside this loop, we use another loop to iterate over the elements of the list again. This inner loop will be used to select the second element of the triplet.

    for j in range(i+1, len(numbers)):

Note that we start the inner loop at i+1 instead of 0. This is because we want to avoid selecting the same element as the first element of the triplet.

Inside this inner loop, we use another loop to iterate over the elements of the list a third time. This innermost loop will be used to select the third element of the triplet.

      for k in range(j+1, len(numbers)):

Again, we start this innermost loop at j+1 to avoid selecting the same element as the first or second element of the triplet.

Now that we have selected all three elements of the triplet (numbers[i], numbers[j], and numbers[k]), we check if the sum of these three elements is equal to 0.

        if numbers[i] + numbers[j] + numbers[k] == 0:

If the sum is equal to 0, we add the triplet to the list of triplets.

          triplets.append((numbers[i], numbers[j], numbers[k]))

After all three loops have completed, we return the list of triplets.

  return triplets

Finally, we call the find_triplets function and print the result to see the triplets that it found.

print(find_triplets([-1, 0, 1, 2, -1, -4]))
# Output: [(-1, 0, 1), (-1, -1, 2)]

Full code.

def find_triplets(numbers):
triplets = []
for i in range(len(numbers)):
for j in range(i+1, len(numbers)):
for k in range(j+1, len(numbers)):
if numbers[i] + numbers[j] + numbers[k] == 0:
triplets.append((numbers[i], numbers[j], numbers[k]))
return triplets

print(find_triplets([-1, 0, 1, 2, -1, -4]))
# Output: [(-1, 0, 1), (-1, -1, 2)]

This function uses three nested loops to iterate over all possible combinations of three numbers in the list. For each combination, it checks if the sum is equal to 0, and if it is, it adds the triplet to the list of triplets. At the end, it returns the list of triplets.

Please do follow me get all the series of google python question for interview with explanation.

--

--

Python Short Codes
Python Short Codes

Written by Python Short Codes

Hi Rajat here, Well versed with predictive modelling, data processing, and data mining algorithms to solve challenging business problems.

No responses yet