10 Python Beginner Level Strings Interview Questions & Answers
Below is a list of our Python Beginner Level Strings 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. Is the sentence a pangram or not?
This interview question tests the developer's skills with Python strings and loops.
You are given a sentence with no white space. The sentence contains only lowercase English letters. You need to check if the sentence is Pangram or not.
Pangram- A pangram is a sentence where every letter of the English alphabet appears at least once.
/*Example*/
given string- 'thequickbrownfoxjumpsoverthelazydog'
expected output- true
given string- 'mynameisjohn'
expected output- false
Solution:
The solution is pretty easy. We will track the occurrence of every alphabet. If there is at least one letter that does not occur in the given sentence, we return False. We will use an array of size 26 with all values equal to False. Then we will iterate over each letter in the given sentence and will put True to the array corresponding to that letter.
In the array,
'a' will have index 0,
'b' will have index 1,
….
'z' will have index 25,
To find the index from the letter, we can subtract 97 from its ASCII value (character code).
'a' has code 97, so will have index 0,
'b' has code 98, so will have index 1,
...
'z' has code 122, so will have index 25,
def isPangram(sentence: str) -> bool:
allAlphabets = [False] * 26
for char in sentence:
ascii_index = ord(char) - ord('a')
allAlphabets[ascii_index] = True
for exists in allAlphabets:
if not exists:
return False
return True
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
2. Return the string in lowercase.
This interview question tests the developer's skills with Python strings and loops.
You are given a string. The string contains the English alphabet. You need to implement a function toLowerCase which returns the same string in lowercase letters. You can not use the inbuilt function str.lower().
/*Example*/
given string- 'abcAGiHkj'
expected output- 'abcagihkj'
given string- 'qwert'
expected output- 'qwert'
Solution:
We will iterate over each character of the given string and convert it into lowercase. Then we will push the resulting character into a result array. After iterating the string, we will join the result array and return it. Now the problem remaining is to convert a character to lowercase.
The lowercase letters have character codes from 97 to 122 (both inclusive) and uppercase have from 65 to 90 (both inclusive). We will check the code of the letter. If it is between 97 and 122, we need not change the character. If it is between 65 and 90, we will add 32 (= 97 - 65) to convert to lowercase. So if-
the letter is 'j'
-> its code is 106
-> between 97 and 122
-> already a lowercase letter
the letter is 'B'
-> its code is 66
-> between 65 and 90
-> add 31
-> 66 + 32 = 98
-> 98 is 'b'
def toLowerCase(string: str) -> str:
result = []
A_ascii = ord('A') # 65
Z_ascii = ord('Z') # 90
for char in string:
ascii_code = ord(char)
if ascii_code >= A_ascii and ascii_code <= Z_ascii:
# change ascii to make capital to lower
char = chr(ascii_code + 32)
result.append(char)
return ''.join(result)
Time complexity- O(n)
Space complexity- O(n)
Written by S. Kumar on June 27th, 2021
3. How many jewels are there?
This interview question tests the developer's skills with Python strings and loops.
You are two given strings- jewels and stones. A jewel is a special and precious stone. All jewels are stones but not vice-versa. Each character of stones represents the type of stones that you have. So if,
stones = 'aAAqbb', you have:
â— one stone of type 'a'
â— two stones of type 'A'
â— one stone of type 'q'
â— two stones of type 'b'
Each character in jewels represents the type of stone that is a jewel. So if,
jewels = 'aA', then:
â— stone of type 'a' is a jewel
â— stone of type 'A' is a jewel
Your task is to find how many stones you have that are jewels
/*Example*/
stones = 'aAAqbb'
jewels = 'aA'
expected output = 3 // ('aAA' are all jewels)
Solution:
The solution is simple. We will iterate over each character in the stones and will check if it is a jewel. To check if a stone is a jewel, we will check if the character is contained in the string jewels.
def findJewels(jewels: str, stones: str) -> int:
count = 0
for stone in stones:
# search for stone in complete jewels array
if stone in jewels:
count += 1
return count
m = length of string jewels
n = length of string stones
Time complexity- O(m * n)
Space complexity- O(1)
There is one optimization we can do. The time complexity of in operator is O(m). Instead of checking if a stone is a jewel using in, we can have a set of stones that are jewels made from string jewels.
set(jewels) converts the string jewels to a set of characters.
So if jewels = 'aA',
set(jewels) = {'a', 'A'}
def findJewels(jewels: str, stones: str) -> int:
count = 0
jewels = set(jewels)
for stone in stones:
if stone in jewels:
count += 1
return count
m = length of string jewels
n = length of string stones
Time complexity- O(n + m)
Space complexity- O(m)
Written by S. Kumar on June 27th, 2021
4. Can you get a string from the binary tree?
This question shows the developer's ability to work with Python recursion.
You are given a binary tree. Your task is to get a string representation of the binary tree. The string consists of parentheses and the values of the nodes in the tree. The representations are as follows-
1. the string representation of a leaf node is the node value itself,
2. the string representation of a null node is '()',
3. for a parent node,
a. its value is written first,
b. the value is followed by the string representation of the left subtree enclosed in pair of
parentheses,
c. then it is followed by the string representation of the right subtree enclosed in pair of
parentheses,
4. you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.
/*Example*/
1.
1
/ \
2 3
/
4
expected output = '1(2(4))(3)'
We didn’t add '()' right child of 2 because those are unnecessary.
2.
1
/ \
2 3
\
4
expected output = '1(2()(4))(3)'
We didn’t omit '()' left child of 2 because omitting those parentheses will 4 as the left child of 2 i.e. same as example-1
Solution:
We can use recursion for this. The required string is the pre-order traversal of the tree. We will get the string representation of both left and right subtrees. If the node is null, we will return an empty string. When we have string representations of left and right subtrees, 4 cases arise-
1. when both left and right children are present i.e. non-empty strings
In this case, the answer will be
node.val + '(' + left-string + ')' + '(' + right + ')'
2. when both left and right children are absent i.e. empty strings
In this case, the answer will be
node.val
3. when only the left child is present i.e. right string is an empty string (example 1)
In this case, we don’t need empty parentheses for the right child
node.val + '(' + left-string + ')'
4. when only the right child is present i.e. left string is an empty string (example 2)
In this case, we must add empty parentheses for the left child
node.val + '()' + '(' + right + ')'
class TreeNode:
def __init__(self, val=0, left=None, right=None) -> None:
self.val = val
self.left = left
self.right = right
def toString(root: TreeNode) -> str:
if not root:
return ''
left = toString(root.left)
right = toString(root.right)
if not left and not right:
return root.val
if not left:
return root.val + '()' + '(' + right + ')'
if not right:
return root.val + '(' + left + ')'
return root.val + '(' + left + ')' + '(' + right + ')'
n = number of nodes in the tree
Time complexity - O(n)
Space complexity - O(n)
The worst-case space complexity is O(n) in the case where the tree is skewed. For example-
1
/
2
/
4
/
3
In this case, there are 4 nodes, and the recursion stack will contain four calls to toString function. Thus O(n) space complexity.
Written by S. Kumar on June 27th, 2021
5. Are the string arrays equivalent?
This interview question concentrates on the developer's abilities with Python join.
You are given two arrays of strings word1 and word2. A string is obtained from an array of strings by joining all the strings in the array. Your task is to check whether the string obtained from both arrays word1 and word2 are equal or not.
/*Example*/
word1 = ['ab', 'c']
word2 = ['a', 'bc']
expected output = true
string from word1 = 'abc'
string from word2 = 'abc'
thus they are equal
word1 = ['ab', 'c']
word2 = ['a', 'cb']
expected output = false
string from word1 = 'abc'
string from word2 = 'acb'
thus they are not equal
Solution:
We will join all the strings in the array by using str.join(list-of-string) method. We will get two strings from the two given arrays. Then, we will compare the strings directly.
def areEqual(word1: List[str], word2: List[str]) -> bool:
string1 = ''.join(word1)
string2 = ''.join(word2)
return string1 == string2
n = total number of characters in word1
m = total number of characters in word2
Time complexity- O(n + m)
Space complexity- O(n + m)
Written by S. Kumar on June 27th, 2021
6. Decipher the string.
This question shows the developer's knowledge of Python strings.
You are given a string consisting of digits and the letter '#'. Your task is to map this given string to a lowercase English string with the following mapping rules:
â— Characters from 'a' to 'i' are represented by '1' to '9' -- (Type I)
â— Characters from 'j' to 'z' are represented by '10#' to '26#' -- (Type II)
/*Example*/
Given string- '12316#'
expected output- 'abcp'
'1' -> 'a'
'2' -> 'b'
'3' -> 'c'
'16#' -> 'p'
Given string- '12#13#14#'
expected output- 'lmn'
'12#' -> 'l'
'13#' -> 'm'
'14#' -> 'n'
Solution:
We will traverse over each character of the given string.
The problem is to determine whether the current character forms a digit from ‘1’ to ‘9’ or from ‘10#’ to ‘26#’.
To solve this we traverse the string from reverse and check for ‘#’ char. As if there exists a two-digit number then it's always followed by a ‘#’ char. So, while traversing the string in reverse, if we first encounter a ‘#’, the1 next two digits will form a single character. We combine two digits to form a number and find the corresponding character. Otherwise, we can convert single digits to ASCII char directly.
First, we convert the string into a stack and then we loop over it till it gets empty.
Initially, we have cipher = ‘812#13#14#’
Then after converting it to stack we have char_list = [‘8’, '1', '2', '#', '1', '3', '#', '1', '4', '#']
Now keep popping the element from the end check if it is ‘#’ then pop two more else use the top element popped just now.
Iteration 1:
result = []
char_list = [‘8’, '1', '2', '#', '1', '3', '#', '1', '4']
top = ‘#’
Then we need to pop two more elements in reverse b = ‘4’ and a = ‘1’ then make a number by concatenating then a + b = ‘14’ then convert it to an integer from string and subtract 1. We have number = 14 - 1 = 13. Then we convert it to a character char = chr( 97 + 13 ) = ‘n’. Now push it on to the result and while returning the result we will reverse the way in which we stored the results.
Iteration 2:
result = [‘n’]
char_list = [‘8’, '1', '2', '#', '1', '3']
top = ‘#’
Then we need to pop two more elements in reverse b = ‘3’ and a = ‘1’ then make a number by concatenating then a + b = ‘13’ then convert it to an integer from string and subtract 1. We have number = 13 - 1 = 12. Then we convert it to a character char = chr( 97 + 12 ) = ‘m’ now push it on to the result and while returning the result we will reverse the way in which we stored the results.
Iteration 3:
result = [‘n’, ‘m’]
char_list = [‘8’, '1', '2']
top = ‘#’
Then we need to pop two more elements in reverse b = ‘2’ and a = ‘1’ then make a number by concatenating then a + b = ‘12’ then convert it to an integer from string and subtract 1. We have number = 12 - 1 = 11. Then we convert it to a character char = chr( 97 + 11 ) = ‘l’ now push it on to the result and while returning the result we will reverse the way in which we stored the results.
Iteration 4:
result = [‘n’, ‘m’, ‘l’]
char_list = []
top = ‘8’
We have top = 8. So number = 8 - 1 = 7. Then we convert it to a character char = chr( 97 + 7 ) = ‘h’ now push it on to the result and while returning the result we will reverse the way in which we stored the results.
End:
result = [‘n’, ‘m’, ‘l’, ‘h’]
char_list = []
Decoded string = ‘hlmn’ (reverse of what we have in result array)
def decipherIt(cipher: str) -> str:
# reverse the cipher string and convert into stack
char_list = list(cipher)
result = []
while char_list:
top = char_list.pop()
if top == '#':
# pop out two char from stack
b, a = char_list.pop(), char_list.pop()
# convert into number and sub 1 to make 'a' as 0 index
number = int(a + b) - 1
else:
number = int(top) - 1
char = chr(ord('a') + number)
result.append(char)
# reverse the result since we collected the char in reverse
return ''.join(result[::-1])
Time complexity- O(n)
Space complexity- O(n)
Written by S. Kumar on June 27th, 2021
7. Remove vowels from the string.
This question focuses on the developer's ability to manipulate strings in Python.
You are given a string. Your task is to remove vowels from the string and return it.
/*Example*/
Given string = 'abcdEFGh'
expected output = 'bcdFGh'
Solution:
We will have a new array result that will store the characters of the resulting string. We will iterate over each character in the string. If the character is a vowel, we will discard it. If it is not a vowel, we will push the character in the result array.
To check if a character is a vowel, we will have another function: isVowel. It will take a character as input. We will check the character if it is included in a string of vowels or not.
def removeVowels(string: str) -> str:
result = []
vowels = set(list('aeiouAEIOU'))
for char in string:
if char in vowels:
continue
result.append(char)
return ''.join(result)
Time complexity- O(n)
Space complexity- O(n)
Written by S. Kumar on June 27th, 2021
8. Count the matching items.
This question focuses on Python iterations.
You are given a 2-D array of items of size n x 3. The array contains n rows of size 3 each. The ith row represents the ith item. The ith item has 3 properties i.e. items[i] = [typei, colori, namei], where typei, colori and namei represents the type, color and the name of the ith item.
You are also given two variables- prop and targetValue. The argument prop is a string with possible values 'type', 'color', and 'name'. Your task is to find the number of items that have the value of prop equal to targetValue.
/*Example*/
Given-
items = [
['phone', 'blue','pixel'],
['computer', 'silver', 'lenovo'],
['phone', 'gold', 'iphone']
]
prop = 'color'
targetValue = 'silver'
Expected output: 1
Explanation: There is only one item that has 'color' equal to 'silver'.
Given-
items = [
['phone', 'blue','pixel'],
['computer', 'silver', 'lenovo'],
['phone', 'gold', 'iphone']
]
prop = 'type'
targetValue = 'phone'
Expected output: 2
Solution:
We will iterate over the array items and will see if the current item has the value of prop equal to targetValue. The value of prop passed is a string with possible values:- 'type', 'color' and 'name' but the properties of the items are indices. So we will map the prop to indices in the items[i] array using the map propsMapping.
def countMatching(items: List[List[str]], prop, targetValue) -> int:
count = 0
propsMapping = {
'type': 0,
'color': 1,
'name': 2,
}
col = propsMapping[prop]
for item in items:
if item[col] == targetValue:
count += 1
return count
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021
9. What is the number of consistent words?
This interview question tests the developer's skills with Python arrays and loops.
You are given an array of words. You are also given another string allowed. A word is consistent if it contains letters that are present in the string allowed. Your task is to count the number of consistent words. The words and the string allowed contain only lowercase English for the ith flower letters.
/*Example*/
words = ['ad','bd','aaab','baa','badabe'] allowed = 'ab'
expected output = 2
Only 'aaab' and 'baa' are consistent because they contain only 'a' and 'b' letters.
'ad' is not consistent because it contains 'd' which is not allowed.
'bd' is not consistent because it contains 'd' which is not allowed.
'badabe' is not consistent because it contains 'd' and 'e' which are not allowed.
Solution:
We can traverse over each character of each word. For a particular word, if all the characters exist in the set allowedChars which is derived from the allowed string, then we say the word is consistent, otherwise not.
def countConsistent(words: List[str], allowed: str) -> int:
allowedChars = set(list(allowed))
count = 0
for word in words:
isWordConsistent = True
for char in word:
if char not in allowedChars:
isWordConsistent = False
break
if isWordConsistent:
count += 1
return count
n = number of words
m = max length of a word
Time complexity- O(n * m)
Space complexity- O(26) = O(1)
Written by S. Kumar on June 27th, 2021
10. Make an anagram.
This question concentrates on a developer's knowledge of Python functions.
You are given two strings src and dest of the same length. The strings contain only lowercase English letters. In one operation, you can choose a character of dest string, and replace it with any other character. Your task is to calculate the minimum number of operations required to make string dest an anagram of src.
A string a is an anagram of b if a contains the same characters with a different (or the same) ordering which are in b.
/*Example*/
src = 'bab' dest = 'aba'
expected output = 1
explanation: we can dest[0] with 'b' to make anagram of src.
Solution:
We will calculate the frequency of each character in both strings. Then we will compare the frequency of each character for both strings. If for some character, dest has a lesser frequency than src, (say the difference is diff), we need to perform a diff number of operations to make the frequency of that character equal. In the above example:
frequency of 'b' in dest = 1
frequency of 'b' in src = 2
So we will perform (2 - 1 = 1) operations to make the frequency of 'b' equal. For the character 'a' the frequencies are already equal.
Also here we use a python inbuilt function zip which used to merge several iterators parallely. Like
first = [1, 3, 5]
second = [2, 4, 6]
Then list(zip(first, second)) = [(1, 2), (3, 4), (5, 6)]
def lettersFrequency(string : str) -> int:
freq = [0] * 26
for char in string:
ascii_index = ord(char) - ord('a')
freq[ascii_index] += 1
return freq
def operationsForAnagram(src: str, dest: str) -> int:
srcCount = lettersFrequency(src)
destCount = lettersFrequency(dest)
operationCount = 0
for src, dest in zip(srcCount, destCount):
diff = src - dest
if diff > 0:
operationCount += diff
return operationCount
Time complexity- O(length of strings)
Space complexity- O(1)
Written by S. Kumar on June 27th, 2021