Essential Python Coding Questions for Data Science Interviews | by Leihua Ye, PhD | Towards Data Science

1
2
3
4
5
6
7
8
9
10
Powered by Play.ht
Create audio with Play.ht
Powered by Play.ht
As the engineering culture keeps growing, Data Scientists often team up with other engineers to build pipelines and perform a ton of soft engineering stuff. Job candidates are expected to face extensive coding challenges in R/Python and SQL (Essential and Tricky SQL).
From my past interview experiences, simply being able to code is far from enough. What differentiates experienced programmers from code-camp-trained beginners is the ability to dissect the big question into smaller pieces and then code it up.
It’s my “aha” moment.
For the past few months, I’ve been deliberately practiced to dissect the code and walk through my thinking processes, as many you may notice if you track my progress. I will do the same for today’s content.
Data manipulation and string extraction are essential components of Data Science Interviews, both as an individual subject or combined with other topics. I’ve elaborated on 6 Python questions for Data Scientists in a previous post and provide additional authentic interview questions asked by major tech companies:
towardsdatascience.com
There is a common misconception in the field, which is using the Brutal Force method isn’t something worth recommending due to its inefficiency and memory usage.
Here, I tend to argue differently. It is extremely helpful for new Python programmers because brutal force solves the problem step by step and reinforces our logical reasoning skills, aka, a better understanding of the question and a better “idea-realization” ability.
Without further ado, let’s dig in
- Write a function that reverses the string.
- sentence = “I love programming in Python. How about you?”
This is a warm-up question but can be complicated after embedding it into a larger question. Anyway, the most straightforward way of reversing a string is to access it backward.
'?uoy tuoba woH .nohtyP ni gnimmargorp evol I'
'?uoy tuoba woH .nohtyP ni gnimmargorp evol I'
If asked for an alternative approach, I’d recommend list comprehension for its simplicity.
- The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.
That is,
F(0) = 0, F(1) = 1,
F(n) = F(n -1) + F(n-2), for n > 1.
- Given n, calculate F(n).
- https://leetcode.com/problems/fibonacci-number/
This is the type of “if-you-know-you-know”question. Interview candidates either love it or hate it, depending on which side they are on. If they are familiar with the shortcut, it’s almost a one-liner coding. Otherwise, it can be unnecessarily tedious and even unsolvable.
First off, I will use brutal force to speak out my thoughts before presenting a better solution. As a rule of thumb, it is a good idea to list some Fibonacci numbers and try to spot any consistent patterns if we code up the naive way.
F(1) = 1.
F(2) = F(1) +F(0) = 1+0 = 1
F(3) =F(2) + F(1) = 1+1 = 2
F(4) = F(3) + F(2) = 2+1 = 3
F(5) = F(4) + F(3) = 3+ 2 = 5
...
Have you found any useful pattern?
As it turns out, this is an iterative process. At each step, we have to update three values sequentially and prepare values for the next iteration. See the following code for detailed explanations.
2
As seen, it becomes unnecessarily tedious when a simple solution exists. Most likely, your interviewers will ask you to improve it.
2
Actually, the Fibonacci number is the ideal scenario for the adoption of recursion. We specify the base condition when n ≤1 and apply the function to itself two times.
Neat solution!
Your interviewer is happy now.
- Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.- A string is represented by an array if the array elements concatenated in order forms the string.- https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/
The question asks if two string arrays are the same. To be the same, they have to contain the same elements and order. For example, the following two arrays are not the same due to different element orders:
word1 = [“a”, “cb”], word2 = [“ab”, “c”]
The brutal method suggests that we can create two new strings and iterate elements from each array into the empty strings, respectively, and decide if they are the same.
True
This is not an optimal solution as it has created two new objects, which take up additional space, and for loops are generally not efficient in terms of speed. Solution 1 causes delays if the data is large.
Your interviewer is not satisfied and asks for improvements.
Well, let’s do solution 2.
True
The join() method is a powerful tool. We can join elements from two arrays into empty strings and check if they are the same without creating anything additional.
Terrific! You passed the interview.
- Given a square matrix mat, return the sum of the matrix diagonals.- Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.- https://leetcode.com/problems/matrix-diagonal-sum/
TBH, I was stuck for good 20 minutes for two reasons. First, I didn’t realize I don’t have to deduct the center element but only when the matrix length is odd. Second, I wasn’t sure how to add elements on the secondary diagonal. After some exploring and checking out others’ Leetcode solutions, I come up with the following code.
8
The Runtime and memory usage are above 80%, according to Leetcode. Is there any better solution for question 4? Please let me know if you know one.
(updated on 1–14, 2021. Thanks to Nebadita Nayak, we have a better solution now.)
Credits to Nebadita Nayak:
- Given the array prices where prices[i] is the price of the ith item in a shop. - There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i], otherwise, you will not receive any discount at all.- Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount.- https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/
I made a mistake for the first trial. I thought j has to be at the next position to i, aka. j = i+1. As it turns out, j could be anywhere as long as it is bigger than i. I didn’t get it until cross-checking my submission with the correct output.
Also, we have to break the for loop once we have found one element; otherwise, the for loop will iterate over the entire array.
The nested for loop takes up a ton of time and has an O(N2) runtime, which can be improved using another data type, stack (link). I’ll write another post on the topic.
- Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.- https://leetcode.com/problems/reverse-words-in-a-string-iii/
This question has several variations. While reading the above information, I have some general direction. To reverse each character but keep the original order, I can split the string using whitespace as the separator. Then, reverse the word via word[::-1] and add whitespaces back between words. Include the rstrip() method to strip away the trailing whitespace.
However, all other steps work except the returning results contain whitespace, which stops me from correctly submitting the code.
def reverse_words(s):    result = “”     new = s.split(“ “)    for word in new:         word = word[::-1]+” “         result += word    result.rstrip()          # don't put it here    return result            # instead, put it here
If I put rstrip() before the return command, it won’t work as intended. It generates the following result with trailing whitespace.
"s'teL ekat edoCteeL tsetnoc "    # trailing whitespace
Every single line of code works fine except for the last one. Bummer! After Googling around, I find that rstrip() has to be at the beginning or end. It won’t work if it’s in the middle.
After fixing the glitch, here we go.
"s'teL ekat edoCteeL tsetnoc"
Again, the rstrip() method has to be in the end or the beginning!
The complete Python code is available on my Github.
I love takeaways because this is the section where I reflect on my past mistakes and learn from them, which is today’s first lesson.
Though brutal force is not recommended, it helps us better understand the underlying logic and document our thinking.
There is no such thing as good coding, as there are always better solutions out there, which is why our interviews keep asking for improvement. Try another data type/structure?
Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees.
leihua-ye.medium.com
towardsdatascience.com
towardsdatascience.com
Please find me on LinkedIn and Youtube.
Also, check my other posts on Artificial Intelligence and Machine Learning.