11 Python Beginner Level Implementation Interview Questions & Answers
Below is a list of our Python Beginner Level Implementation interview questions. Click on any interview question to view our answer advice and answer examples. You may view 5 answer examples before our paywall loads. Afterwards, you'll be asked to upgrade to view the rest of our answers.
1. Validate a square.
This interview question shows a developer's knowledge of Python functions.
You are given four points in 2-D space. Return true if they form a square, false otherwise. The points are integer coordinates and are given in any order.
Valid square- A quadrilateral with all sides equal and both diagonal equal. Also, each interior angle is equal to 90°.
/*Example*/
Input- [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Expected output- true
Input- [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]
Expected output- false
Solution:
For four points, we can find distances between them. There are a total of 6 distances possible. To be a valid square, 4 of them should be equal (the sides) and 2 should be equal (diagonals), and satisfies the following condition (Pythagoras theorem)-
diagonal2 = 2 * side2
Instead of storing actual sides or diagonal, we are storing their square to avoid precision loss due to imperfect squares.
from collections import defaultdict
def distance(p, q):
'''
function returns the square of the distance
bw two point p and q
'''
delta_x = p[0] - q[0]
delta_y = p[1] - q[1]
return (delta_x ** 2) + (delta_y ** 2)
def isValidSquare(p1, p2, p3, p4):
'''
1. Out of 6 distance combination 2 of one type (diag)
and 4 of one type (diag)
2. side_sq * 2 = diag_square
'''
points = [p1, p2, p3, p4] # all points in one iterable
distances = [] # to record dist in btw all points
# for 6 diff combinations
for i in range(3):
for j in range(i + 1, 4):
distances.append(distance(points[i], points[j]))
# count occurance of all distances in distances array
# and count their frequencies (how many time each value occur)
counts = defaultdict(int)
for ele in distances:
counts[ele] += 1
# only two distinct distance (side and diag) else return false
if len(counts) != 2:
return False
# iterate and get the side and diagonal actual value
side_square = diag_square = None
for key, value in counts.items():
# break out of loop as soon we get both values
if side_square and diag_square:
break
if value == 2: # diag have freq of two
diag_square = key
elif value == 4: # side have freq of four
side_square = key
# sq of diag is equal to 2 times sq of sides
if side_square * 2 == diag_square:
return True
return False
Time complexity- O(1)
Space complexity- O(1)
Written by Jennie Taylor on May 21st, 2021
2. Format a string by grouping characters found in the string into similar lengths.
This question tests that a developer is familiar with Python textual data.
You are given a string named string consisting of alphanumeric characters. It contains some dashes - at random places dividing the string into groups. These groups can be of different or the same length. Your task is to format the string such that the dashes divide the string into groups of equal length K. The first group may have a length of less than or equal to K but the rest of the groups must have length K.
/*Example*/
Given - “abc-def†and K = 2
Expected output - “ab-cd-efâ€
All groups have the same length 2.
Given - “abc-def-abdj-k†and K = 3
Expected output - “ab-cde-fab-djkâ€
All groups have except the first group has the same length 3.
Solution:
Given string - string
Let, the normal length of groups (except for the first group) be K
Let, the length of the given string be L
Let, the count of alphanumeric characters be N
If K divides N, then there are exactly K // N such groups in the formatted string each of length K.
If K does not divide N, then there are K // N groups each of length K and one group with remaining characters. The first group will have fewer than K characters and the rest will have exactly K characters. It is guaranteed that its length will be at least 1 because K does not divide N. We can obtain the remaining characters using modulo operator K % N.
Let’s understand the sample inputs.
Given string- “abc-defâ€
Given K = 2
N = 6
Since K divides N, there will be 6 / 2 = 3 groups in the formatted string.
Given string- “abc-def-abdjkâ€
Given K = 3
N = 11
Since K does not divide N, there will be 11 // 3 = 3 groups in the formatted string with length K = 3 viz. cde, fab, djk. The remaining two characters ab will form the first group with length <= K = 3.
def formatLicenseKey(string, k):
'''
separate elements from string which can't be
part of block of size k each.
'''
# remove all '-' from string and concat back
# to get simple string
hypen_removed_string = ''.join(string.split('-'))
length = len(hypen_removed_string)
# get the number of char which can't fit in block
# of k elements each
extra_chars = length % k
# get extra characters from front of string
prefix = hypen_removed_string[:extra_chars]
remaining = hypen_removed_string[extra_chars:]
# make chunks of size k
lst = []
for i in range(0, len(remaining), k):
lst.append( remaining[i : i + k] )
remaining_string = '-'.join(lst)
if prefix:
return prefix + '-' + remaining_string
return remaining_string
Time complexity- O(n)
Space complexity- O(n)
Written by Jennie Taylor on May 21st, 2021
3. How do you find two integers in the array such that their sum is 'target'?
This question focuses on the developer's knowledge of loops.
You are given an array nums and an integer target. Your task is to find two integers in the array such that their sum is target. You need to return their indices. It is guaranteed that exactly one solution exists.
/*Example*/
nums = [17, 15, 2, 9] target = 24
expected output:- [1, 3]
explanation:- The sum of integers at indices at 1 and 3 is 24 (15 + 9).
nums = [7, 8, 5, 3, 1] target = 4
expected output:- [3, 4]
explanation:- The sum of integers at indices at 3 and 4 is 4 (3 + 1).
Solution:
Approach I (Brute force):
Brute force and search for all possible combinations return the index of elements whose sum is equal to the target. This is n2 on time complexity but constant space complexity.
def findTwoSum(nums, target):
n = len(nums)
for i in range(n):
for j in range(n):
sums = nums[i] + nums[j]
if i != j and sums == target:
return [i, j]
Time complexity- O(n2)
Space complexity- O(1)
Approach II (using maps):
We will iterate over the array. We will maintain a map to store the number and their indices. The numbers will be the keys and their indices will be the values of the map.
Let curr be the current number. We will check if target - curr exists in the map, which means we have got our two required numbers and will return their indices.
If target - curr does not exist, we will save curr to the map.
def findTwoSum(nums, target):
# make a map or dictionary
indices = {}
for index, ele in enumerate(nums):
indices[ele] = index
for ele in nums:
complement = target - ele
if complement in indices:
return [indices[ele], indices[complement]]
Time complexity- O(n)
Space complexity- O(n)
Written by Jennie Taylor on May 21st, 2021
4. How do you determine if a string is valid or not?
This interview question focuses on Python methods.
You are given string str. The string consists of characters “(“, “)â€, “{“, “}â€, “[“ and “]â€. Your task is to determine if str is valid or not. A string consisting of valid if it contains:-
◠every opening bracket is closed by a closing bracket of the same type (“(){}[()]†is valid while “(){[]†is not valid), and
◠the opening and closing brackets are in the correct order (“()[]†is valid but “)(†and “({)}†are not valid).
/*Example*/
str = “()â€
expected output = true
str = “()[]{}â€
expected output = true
str = “(]â€
expected output = false
str = “({)}â€
expected output = false
Solution:
We will iterate over the passed string. We will use a stack to track the opening brackets. If the current bracket is an opening bracket i.e. one of “(“, “{“ and “[“, we will push it to the stack. If the current bracket is a closing bracket, then:-
â— If the stack is empty, it means there is no matching opening bracket in the stack. So return false.
â— If the stack is not empty. we will pop an opening bracket from the stack. The popped opening bracket and the current closing bracket is of the same type, we will continue with the next bracket. If they are not of the same type, we will return false.
After iterating over all the brackets, if the stack is empty, we return true. If it is not empty, we return false because it means, there are some opening brackets that are not matched yet.
def isValidString(string):
'''
Iterate and put each incoming bracket in stack and pop
the bracket on top of the stack if the next coming
bracket is in pairs of that bracket.
If stack is empty then push the current
bracket to top of stack
'''
stack = [] # get an empty stack
matching = {
# opening part can complement it's closing part
'{': '}',
'(': ')',
'[': ']',
# to avoid KeyError, as a closing part on top of
# stack can't complement it's opening part
# or any other bracket
'}': "",
']': "",
')': ""
}
for bracket in string:
if stack and matching[stack[-1]] == bracket:
stack.pop()
continue
stack.append(bracket)
# in case of balanced string the stack must be empty in end
return len(stack) == 0
Time complexity- O(n)
Space complexity- O(n)
Written by Jennie Taylor on May 21st, 2021
5. How can you find the third largest number in an array?
This question works with Python methods and loops.
You are given an array of integers. Your task is to find the third-largest number in the array. It is guaranteed that the answer always exists.
/*Example*/
nums = [5, 9, 1, 7, 8]
expected output = 7
Solution:
Approach I (Sorting):
Remove the duplicate from the array and then sort the array in ascending order. If array length is least 3 or more then choose the third element.
def findThirdLargest(nums):
# remove duplicate elements
nums = list(set(nums))
# sort the list in ascending order
nums.sort(reverse=True)
# return the third element from front
return nums[2]
Time complexity- O(nlogn)
Space complexity- O(1)
Approach II (Iterating):
We will iterate over all the numbers. We will have three variables:- firstMax, secondMax and thirdMax. They all are initialized to -Infinity. Let curr be the current number:-
â— If curr is larger than firstMax, the new value of firstMax will be curr, and the new value of secondMax will be old value firstMax, and the new value of thirdMax will be old value secondMax.
â— If curr is larger than secondMax (and smaller than firstMax), the new value of secondMax will be old value curr, and the new value of thirdMax will be old value secondMax.
â— If curr is larger than thirdMax (and smaller than secondMax), the new value of thirdMax will be the old value curr.
â— If curr is smaller than thirdMax, all values will be unchanged.
def findThirdLargest(nums):
# remove repeated elements
nums = list(set(nums))
first = second = third = float('-inf')
for ele in nums:
if ele > first:
first, second, third = ele, first, second
elif ele > second:
second, third = ele, second
elif ele > third:
third = ele
return third
Time complexity- O(n)
Space complexity- O(1)
Written by Jennie Taylor on May 21st, 2021
6. Find if the array contains a unique number of occurrences for each value in the array or not.
This interview question shows the developer's knowledge of filtering in Python.
You are given an array of integers. Your task is to find if the array contains unique frequencies for each value in the array or not.
/*Example*/
arr = [1, 2, 2, 1, 1, 3]
expected output = true
freq of 1 = 3
freq of 2 = 2
freq of 3 = 1
The frequencies are unique for each value, so we return true.
arr = [1,2]
expected output = false
freq of 1 = 1
freq of 2 = 1
The frequencies are not unique for each value, so we return false.
Solution:
Count frequency of each element in the array and then to check if all those frequencies are different (unique) check whether the number of unique frequencies is equal to number of unique keys available in map.
from collections import defaultdict
def hasUniqueFreq(arr):
'''
Count frequencies of each element in array and check if
all those frequencies are different
'''
elements = defaultdict(int)
# count freq of all ele in array
for ele in arr:
elements[ele] += 1
# get all value in a set which removes any duplicate value
freq = set(list(elements.values()))
# if all elements have diff frequencies
# then there are as many distinct value as there are keys
return len(freq) == len(elements)
Time complexity- O(n)
Space complexity- O(n)
Written by Jennie Taylor on May 21st, 2021
7. Create a running sum of a 1-D array.
This question focuses on Python functions.
You are given an array nums of integers. Your task is to find a new array runningSum such that runningSum[i] = sumOf(nums[0], nums[1], …, nums[i]).
/*Example*/
Given nums = [1, 2, 3, 4]
Expected output:- [1, 3, 6, 10]
Explanation:-
runningSum = [1, 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4] = [1, 3, 6, 10]
Given nums = [4, 3, 2, 1]
Expected output:- [4, 7, 9, 10]
Explanation:-
runningSum = [4, 4 + 3, 4 + 3 + 2, 4 + 3 + 2 + 1] = [4, 7, 9, 10]
Solution:
We will create a new array runningSum. We will set runningSum[0] = nums[0] because the first element in both the array is the same. Now,
runningSum[i] = sum of all elements in nums from 0 to i
runningSum[i + 1] = sum of all elements in nums from 0 to (i + 1)
= (sum of all elements in nums from 0 to i) + nums[i + 1]
runningSum[i + 1] = runningSum[i] + nums[i + 1]
def findRunningSum(arr):
result = [0]
for ele in arr:
result.append( result[-1] + ele )
return result[1:]
Time complexity- O(n)
Space complexity- O(1)
Written by Jennie Taylor on May 21st, 2021
8. Determine if str1 is a subsequence of str2.
This question tests the developer's ability to work with Python sequences.
You are given two strings str1 and str2. Your task is to find if str1 is a subsequence of str2.
A subsequence of a string is a string that is created from the original by deleting zero or more characters with the order of remaining characters the same as the original string.
So if the original string is “abcdeâ€, the possible subsequences are:
◠“abcdeâ€:- deleting no zero characters.
◠“abdeâ€:- deleting “câ€
◠“bdeâ€:- deleting “a†and “câ€
but these are not valid subsequences:
◠“aebâ€:- the relative order is not the same
◠“cbzâ€:- contains other character “z†which is not in original string
/*Example*/
str1 = “abcâ€, str2 = “ahbgdcâ€
expected output- true
str1 = “axcâ€, str2 = “ahbgdcâ€
expected output- false
Solution:
Keep a count of the character we traversed in both the strings. As soon a character of first string matched with second string then we increment the pointer to first string. If first is the subsequence of second then by the end of traversal of second string we would also reach the end of first string.
def SubSequenceString(first, second):
m = len(first)
n = len(second)
i = j = 0
# whenever a char of first match with second
# than we increment the pointer pointing to
# character's in first (i)
while i < m and j < n:
if first[i] == second[j]:
i += 1
j += 1
# if the pointer of first string reach till the end then
# first is subsequence of second
return i == len(first)
Time complexity- O(n)
Space complexity- O(1)
Written by Jennie Taylor on May 21st, 2021
9. Find the largest two numbers in an array without sorting them.
This question focuses on knowledge of arrays in Python.
You are given an unsorted array of integers. Your task is to find the two largest elements in the array without sorting them. Return the two integers in the array of size two, the largest at index-0 and the second-largest at index-1.
/*Example*/
Given- [1, 3, 2, 5, 4]
expected output- [5, 4]
Solution:
Traverse the array and then keep updating the first and second largest element in the array.
def findSecondLargest(nums):
first = second = float('-inf')
for ele in nums:
if ele > first:
first, second = ele, first
elif ele > second:
second = ele
return [first, second]
Time complexity- O(n)
Space complexity- O(1)
Written by Jennie Taylor on May 21st, 2021
10. Find unique vanishing numbers.
This question tests the developer's ability to use Python methods.
You are given an integer n. Your task to generate and return an array consisting of unique integers such that they all add up to 0. You can return any array that satisfies the property.
/*Example*/
Given n = 5
expected output:- [1, 2, -3, 4, -4]
other possible answers:-
[0, 1, 2, -1, -2]
[-4, -3, 5, 2, 0] and many more...
Solution:
If N is even then choose equal numbers of positive and negative numbers. While if N is odd then we take equal numbers of positive and negative numbers and include one 0.
def generateArray(n):
return list(range(1 - n, n, 2))
Time complexity- O(n) .. In inserting all n elements
Space complexity- O(n) .. list get generated in memory
Written by Jennie Taylor on May 21st, 2021
11. Find if the robot returns to its home after given instructions or not.
This question focuses on Python functions.
There is a robot initially at its home- the origin on a 2D plane. It is given some instructions to move to either left or right or up or down. The robot moves the same distance at each instruction in any direction. You are given a string moves consisting of letters “Lâ€, “Râ€, “U†and “D†corresponding to left, right, up and down respectively. The string moves tell the series of instructions given to the robot. Your task is to find if the robot returns to its home after these instructions or not.
/*Example*/
Given moves = “LUDRâ€
expected output = true
Given moves = “LLRâ€
expected output = false
Solution:
All moves must be equal in numbers to their complementary move. Number of left moves must be equal to the number of right moves and the number of up moves must be equal to the number of down moves.
def BackToHome(moves):
# rules to update coordinates as per moves
coordinates = { 'L': -1, 'R': 1, 'U': 1, 'D': -1 }
# define the starting coordinates
x = y = 0
for move in moves:
if move in 'LR':
x += coordinates[move]
else:
y += coordinates[move]
return x == 0 and y == 0
Time complexity- O(n)
Space complexity- O(1)
Written by Jennie Taylor on May 21st, 2021