12 Python Beginner Level Arrays Interview Questions & Answers
Below is a list of our Python Beginner Level Arrays 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. Find integers smaller than the current number.
This question proves the developer's ability to work with elements.
You are given an array of integers num. Your task is to find the count of integers that are less than num[i] for every integer num[i] in the array num. You need to return these counts in an array count, with count[i] representing the count of integers less than num[i].
/*Example*/
num = [5, 1, 2, 2, 4, 3, 10, 3]
expected result- [6, 0, 1, 1, 5, 3, 7, 3]
for num[0] = 5, there are 6 integers smaller than 5 (1, 2, 2, 4, 3, 3)
for num[1] = 1, there are 0 integers smaller than 1
for num[2] = 2, there is 1 integer smaller than 2 (1)
for num[2] = 2, there is 1 integer smaller than 2 (1)
for num[3] = 4, there are 5 integers smaller than 4 (1, 2, 2, 3, 3)
for num[4] = 3, there are 3 integers smaller than 3 (1, 2, 2)
for num[5] = 10, there are 7 integers smaller than 10 (5, 1, 2, 2, 4, 3, 3)
for num[6] = 3, there are 3 integers smaller than 3 (1, 2, 2)
Solution:
First, we need to count the number of integers that are less than integer num[i]. To find this, we can make a copy of the given and sort it. Then, the count of integers less than sorted[i] will be equal to I:
Given array- num = [5, 1, 2, 2, 4, 3, 10, 3]
Sorted array- sorted = [1, 2, 2, 3, 3, 4, 5, 10]
For 1, index = 0, so count of integers less than 1 = 0
For 2, index = 1 (we will see smallest index), so count of integers less than 2 = 1
For 3, index = 3 (we will see smallest index), so count of integers less than 3 = 3
For 4, index = 5, so count of integers less than 4 = 5
For 5, index = 6, so count of integers less than 5 = 6
For 10, index = 7, so count of integers less than 10 = 7
We will store these counts in a map, where the keys will be the integer itself and the values will be the count of integers less than that integer. So resulting map will be:
{
1 -> 0
2 -> 1
3 -> 3
4 -> 5
5 -> 6
10 -> 7
}
Then, we will create a result array count and will store counts corresponding to each element num[i].
def findSmallerIntegers(nums):
sorted_nums = sorted(nums)
lesser_than_count = {}
for i, num in enumerate(sorted_nums):
# if ele is not already present than update its
# entry in map with value equal to index i of
# num in sorted array
if num not in lesser_than_count:
lesser_than_count[num] = i
# for each element in nums take it's lesser than count
return [lesser_than_count[ele] for ele in nums]
Time complexity- O(n)
Space complexity- O(n)
Written by S. Kumar on June 27th, 2021
2. Create a solution to return a rearranged array.
This interview question concentrates on Python functions.
You are given array nums. It contains 2*n elements in form of-
[x1, x2, x3, …, xn, y1, y2, y3, …, yn]
Rearrange the given array to make in form of-
[x1, y1, x2, y2, x3, y3, …, xn, yn]
You have to return a solution in a new array.
/*Example*/
nums = [1,2,3,4,4,3,2,1], n = 4
expected = [1,4,2,3,3,2,4,1]
Solution:
We need to place the first n number to even indices (0-indexed) of the result array, and place next n elements to odd indices. This makes the solution pretty straightforward.
Create a new result array of size 2 * n. Copy first n number to even indices, that is 2 * I, and other n elements to odd indices, that is 2 * i + 1.
def shuffle(nums, n):
result = [0] * 2 * n
for i in range(n):
result[2 * i] = nums[i] # for even places
result[2 * i + 1] = nums[i + n] # for odd places
return result
Time complexity- O(n)
Space complexity- O(n)
Written by S. Kumar on June 27th, 2021
3. How do you find the sum of unique elements?
This interview question concentrates on using Python occurrences in arrays.
You are given an array of integers. You have to find the sum of all those elements which occur exactly once.
/*Example*/
nums = [1, 3, 4, 3]
expected output = 1 + 4 = 5 (3 occurs two times, so will be neglected)
nums = [2, 2, 3, 2, 3]
expected output = 0 (all numbers occur more one time)
Solution:
We will count the occurrences of each number on a map. The keys of the map will be the numbers and the values will be the count of their occurrences. Then we will iterate over every key of the map and will add it to the sum if its occurrence is equal to 1.
from collections import Counter
def sumUnique(nums):
freq_count = Counter(nums)
result = 0
for ele, count in freq_count.items():
if count == 1:
result += ele
return result
Time complexity- O(n)
Space complexity- O(n)
Written by S. Kumar on June 27th, 2021
4. Can you find the richest person and return their wealth?
This interview question focuses on working with Python objects.
You are given a 2-D array of accounts of size n x m. The row accounts[i] represent an array of bank accounts of the ith person. The accounts[i][j] represent the wealth of ith person in the jth bank. Your task is to find the richest person and return their wealth. The total wealth of a person is the sum of all money they have in their bank accounts. The richest person is the person with the highest wealth.
/*Example*/
accounts = [[2,8,7],[7,1,3],[1,9,5]]
wealth of 0th person = 17 (sum of 0th row)
wealth of 1st person = 11 (sum of 1st row)
wealth of 2nd person = 15 (sum of 2nd row)
wealth of richest person = 17
Solution:
We will calculate the wealth of each person and then will find the person with the highest wealth.
def findRichest(accounts):
mx = 0
for i in range(len(accounts)):
mx = max(sum(accounts[i]), mx)
return mx
def findRichest(accounts):
# determine maximum element (a list) from matrix
# based on 'sum' as key, then after return sum of that
# maximum element
richest_person = max(accounts, key=sum)
richest_person_wealth = sum(richest_person)
return richest_person_wealth
Time complexity- O(n2)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
5. Create a target array in a given order.
This question focuses on the developer's knowledge of Python methods.
You are given two array nums and indices of the same size. Your task is to create a new array from these given arrays.
Let the resulting array be res. res is empty at first.
You iterate over the given arrays from left to right (i.e. from lower index to higher index).
Let i be the current index.
You will insert the number nums[i] at index indices[i]
/*Example*/
nums = [1, 2, 3, 4, 5]
indices = [0, 1, 2, 2, 1]
expected = [1, 5, 2, 4, 3]
explanation:
i nums[i] index[i] res
0 1 0 [1]
1 2 1 [1, 2]
2 2 2 [1, 2, 3]
3 4 2 [1, 2, 4, 3]
4 5 1 [1, 5, 2, 4, 3]
Solution:
We will create a new empty array res. We will iterate over each element of given arrays from index 0. We will insert nums[i] at index[i] directly. We will use the insert method for this.
def createTargetArray(nums, indices):
result = []
for i in range(len(nums)):
result.insert(indices[i], nums[i])
return result
Time complexity- O(n2)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
6. How do you sort by parity?
This question concentrates on Python loops and sorting.
You have an array of positive numbers. Your task is to rearrange the array so that all odd numbers follow all even numbers. The order of the even numbers or odd numbers is not important
/*Example*/
Given array- [1, 2, 3, 4, 5, 6]
expected = [2, 4, 6, 1, 3, 5]
also accepted = [4, 6, 2, 1, 5, 3]
Solution:
Approach I (sort):
We can sort the array using a custom function passed to the sort function. There is one argument 'ele' passed to the custom function. The function should return:
1: If the element is odd
-1: If the element is even
Elements that return -1 (even) are treated smaller in value and hence sorted towards the front and those who return 1 (odd) are treated larger in value.
We want to have even numbers before odd numbers, which means all even numbers are “less than†all odd numbers.
def sortByParity(nums):
parity_sort = lambda ele: 1 if ele % 2 else -1
return sorted(nums, key=parity_sort)
Time complexity- O(n logn)
Space complexity- O(1)
Approach II (Two-pass):
We can create a new empty result array. Then we run two loops.
1. In the first loop, we will push only even numbers.
2. In the second loop, we will push only odd numbers.
def sortByParity(nums):
even = [ele for ele in nums if ele % 2 == 0]
odd = [ele for ele in nums if ele % 2 != 0]
return even + odd
Time complexity- O(n)
Space complexity- O(n)
Approach III (Two pointers):
We will start at the two ends of the given array nums. i on the left (index 0), and j on right (index size - 1).
â— from the left side, we will find the first odd number i.e. first i such that nums[i] is odd,
â— from the right side, we will find the first even number i.e. first j (while decreasing j from size - 1 to 0) such that nums[j] are even,
â— then we will swap nums[i] and nums[j] so that index i has an even number and index j has an odd number after the wap. After the swap, all the numbers from index 0 to index i are even number, and all the numbers from j to size - 1 are all odd,
â— then we will increase i by 1 and decrease j by -1 and repeat the process until i and j cross each other.
2 4 3 1 6 8 5 7 9 11
--> i j <--
After swap-
2 4 8 1 6 3 5 7 9 11
--> i j <--
Next iteration-
2 4 8 1 6 3 5 7 9 11
--> i j <--
After swap
2 4 8 6 1 3 5 7 9 11
--> i j <--
Next iteration-
2 4 8 1 6 3 5 7 9 11
j<-- -->i (i and j cross each other, stop here)
def sortByParity(nums):
i, j = 0, len(nums)-1
while i < j:
# skip even numbers from beginning
while i < j and nums[i] % 2 == 0:
i += 1
# skip odd numbers from end
while i < j and nums[j] % 2 != 0:
j -= 1
# swap the two numbers
nums[i], nums[j] = nums[j], nums[i]
# move pointer in respective directions
i += 1
j -= 1
return nums
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
7. What ways can you reach the top of the steps?
This question works with a Python algorithm.
You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
/*Example 1*/
Given n = 3
Expected output = 3
Explanation: There are in total 3 distinct ways to go the top
1. 1 step + 1 step + 1 step
2. 2 steps + 1 step
3. 1 step + 2 steps
Example 2
Given n = 5
Expected Output = 8
Explanation: For n as 5 there are 8 distinct ways to go the top
1. 1 step + 1 step + 1 step + 1 step + 1 step
2. 1 step +1 step + 1 step + 2 steps
3. 1 step + 1 step + 2 steps + 1 step
4. 1 step + 2 steps + 1 step + 1 step
5. 2 steps + 1 step + 1 step + 1 step
6. 1 step + 2 step + 2 step
7. 2 steps + 2 steps + 1 step
8. 2 steps +1 steps + 2 steps
Solution:
For n = 2 Expected Output = 2
â— We can go to Level 2 in 2 ways.
â—‹ Either we take the single step two times.
â—‹ We take two steps one time.
For n = 3 Expected Output = 3
â— We can go to Level 2 in 2 ways.
â—‹ Either we take the single step three times.
â—‹ We first take two steps one time and then a single step.
â—‹ We take one step first then two steps.
After we have taken the first step notice how the larger problem of taking 3 steps have now reduced to
â— waysToTake3Steps = 1 + waysToTake2Steps + 2 + waysToTake1Step
We can thus see how the number of ways to take any step for (n>=3) is the sum of the number of ways to take the (n-1) steps + the number of ways to take (n-2) steps.
Approach I (Recursive):
The first approach is fairly simple. First, we will check if n is 1 return 1 if it is 2 return 2.If n >= 3 we find the sum of n - 1 and n - 2 recursively.
But this solution becomes very slow for larger values since we are doing a lot of recalculations.
def distinctWays(n):
if n == 0: return 0
if n == 1: return 1
if n == 2: return 2
return distinctWays(n - 1) + distinctWays(n - 2)
Time complexity- O(2n) // where n is the number of stairs which is also the maximum height of a binary tree.
Space complexity- O(n) // stack size while makin
Approach II (Iterative):
With recursion, we are recalculating a lot of values. To optimize we maintain a cache array. First, we need to set the values of a = 1 and b = 2. In each iteration, b becomes equal to the sum previous of a and b.
def distinctWays(n):
if n == 0: return 0
a, b = 1, 2
# loop follow same pattern as
for i in range(n - 1):
a, b = b, a + b
return a
Time complexity- O(n) where n is the number of steps
Space complexity- O(n)
Written by S. Kumar on June 27th, 2021
8. Create a code to return the maximized sum.
This question shows the developer's understanding of Python functions.
You have given an array nums of size 2 * n. Group these integers into n pairs (a1, b1), (a2, b2), …, (an, bn) such that the sum of min(ai, bi) for all i is maximized. Your task is to return the maximized sum.
/*Example*/
Given nums = [1, 4, 3, 2]
expected output = 4
explanation:
â— (1, 4) + (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
â— (1, 2) + (4, 3) -> min(1, 2) + min(4, 3) = 1 + 3 = 4
â— (1, 3) + (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
Solution:
The key observation here is:- we can not pair the smallest number with the greatest number, or the second smallest with the second greatest, and so on.
Let’s say we have 4 numbers a, b, c and d in sorted order. We have to pair a with another number. Since a is the smallest number, there will be the contribution of a in the final sum irrespective of the other number we choose:-
â— min(a, b) = a
â— min(a, c) = a
â— min(a, d) = a
So it is optimal to choose b out of b, c, and d to pair with a. A similar argument holds for other numbers.
In the solution, first, we sort all the numbers in ascending order. Then we pair even-indexed numbers with odd-indexed numbers i.e. index 0 with index 1, index 2 with index 3, and so on. The resulting answer will be the sum of all numbers at even indices because
nums[0] <= nums[1]
=> min(nums[0], nums[1]) = nums[0]
def pairSum(nums):
nums.sort()
result = 0
for i in range(0, len(nums), 2):
result += nums[i]
return result
Time complexity- O(n logn)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
9. Find which kids can be happy after extra candy.
This interview question concentrates on using Python methods and arrays.
n kids are having some candies. You are given an array of candies. The ith kid has candies[i] number of candies. There are some extraCandies. You want to distribute extraCandies to the kids.
A kid is happy if she has the greatest number of candies among all the kids. Your task is to find which kids can be happy after distributing extraCandies to them. A kid may get possibly all or none of the extraCandies.
/*Example*/
Given candies = [2,3,5,1,3] extraCandies = 3
Expected output = [true, true, true, false, true]
Explanation:
kid with the maximum number of candies has 5 candies
kid 0 is happy if she gets all the 3 extraCandies
kid 1 is happy if she gets at least 2 extraCandies
kid 2 has already the greatest number of candies
kid 3 can never be happy even if she gets all the 3 extraCandies
kid 4 is happy if she gets at least 2 extraCandies
Solution:
The solution is pretty easy. First, we will find the maximum number of candies a kid has. Afterward, we will try to give all the extra candies to one kid and then check if she is happy or not.
def happyKids(candies, extraCandies):
max_candies = max(candies)
result = []
for candie in candies:
isHappy = candie + extraCandies >= max_candies
result.append(isHappy)
return result
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
10. Can you find the highest altitude?
This interview question focuses on Python loops.
A biker is on a road trip in a hilly area. There are a total of n + 1 stops where the rider stops. The biker starts at stop 0 at an altitude of 0.
You are given an array gain of size n. It represents the gain in altitude of the current stop from the previous stop. More formally,
gain[i] = (altitude of stop [i + 1]) - (altitude of stop [i])
Your task is to find the stop with the highest altitude and return its altitude.
/*Example*/
gain = [-5, 1, 5, 0, -7]
expected output = 1
explanation: The altitudes are [0, -5, -4, 1, 1, -6]. The highest altitude is 1.
Solution:
The solution is pretty simple. We will traverse over each gain. We will find the altitude of the current stop using the gain and the altitude of the previous stop (calculated in the previous iteration). We will check it with the maximum altitude we got so far.
def getHighestAltitude(gain):
mx = 0
currAltitude = 0
for g in gain:
currAltitude += g
mx = max(mx, currAltitude)
return mx
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
11. What is the diagonal sum?
This interview question concentrates on the developer's ability to work with Python functions.
You are given a square matrix mat. Your task is to calculate the sum of all the diagonal elements of the array.
/*Example*/
Given mat =
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
expected output = 25 (1 + 5 + 9 + 3 + 7)
Given mat =
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]
expected output = 8
Solution:
The solution is pretty simple. We will iterate over all the matrix diagonal elements and add them to the sum. One thing to note is that, when the matrix is of odd dimension, the middle diagonal element is counted twice. So we will subtract at last.
def diagonalSum(mat):
total = 0
n = len(mat)
for i in range(n):
total += mat[i][i]
total += mat[i][n - i - 1]
# if matrix if of odd length
# subtract the middle element
if (n % 2 == 1):
mid = n // 2
total -= mat[mid][mid]
return total
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
12. Find squares of a sorted array.
This question tests the developer's ability to work with Python sort and pointers.
You are given a sorted array of integers in ascending order. Your task is to find the square of each integer and return them in a sorted array.
/*Example*/
Given array = [1, 2, 3, 4, 5]
expected output = [1, 4, 9, 16, 25]
Given array = [-4, -1, 0, 3, 10]
expected output = [0, 1, 9, 16, 100]
Solution:
Approach I (using sort):
This is the easiest approach. We will create a new result array. We will iterate over the given numbers. For each number, we will push its square to the result. After that, we will sort the result array.
def sortedSquares(nums: List[int]) -> List[int]:
return sorted([num * num for num in nums])
Time complexity- O(n logn) # sorting
Space complexity- O(n) # a new array object gets created
Approach II (two pointers):
In this approach, we will find the index of the smallest non-negative number (numbers greater than or equal to zero). Let the index is idx. Then we will have two pointers i and j (pointers mean indices of the array here). The i will run on all non-negative numbers (from idx to last of the array) and j will run on the negative numbers in the backward direction (from idx - 1 to 0). We will compare numbers at indices i and j, and will push the square of the smaller number and advance its pointer. For example, for given array [-4, -1, 0, 3, 10],
-4 -1 0 3 10
|
idx
-4 -1 0 3 10
| |
j i result = []
-4 -1 0 3 10
| |
j i result = [0]
-4 -1 0 3 10
| |
j i result = [0, 1]
-4 -1 0 3 10
| |
j i result = [0, 1, 9]
-4 -1 0 3 10
| |
j (value of j is -1 here) i result = [0, 1, 9, 16]
-4 -1 0 3 10
| |
j (value of j is -1 here) i result = [0, 1, 9, 16, 100]
When the value of j is -1, it means we have traversed all negative numbers and pushed their squares in the correct order. In this case nums[j] = num[-1] = Index out of bound error. So we put a default value Infinity using the ternary operator.
When the value of i is 5 (length of the array), it means we have traversed all non-negative numbers and pushed their squares in the correct order. In this case nums[i] = num[5] = undefined. So we put a default value Infinity using the ternary operator.
def sortedSquares(nums: List[int]) -> List[int]:
result = []
n = len(nums)
for idx, num in enumerate(nums):
if num >= 0:
break
i, j = idx, idx - 1
while j > -1 or i < n:
numsI = nums[i] if i < n else float('inf')
numsJ = nums[j] if j > -1 else float('inf')
if numsI < abs(numsJ):
result.append(numsI * numsI)
i += 1
else:
result.append(numsJ * numsJ)
j -= 1
return result
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021