How to Solve Python Coding Questions using Math | 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
Python coding interviews come in different shapes and forms, and each type has its unique characteristics and approaches. For example, String Manipulation questions expect candidates to have a solid grasp of element retrieval and access. Data Type Switching questions test your understanding of the tradeoffs and unique traits with each type.
However, the math question is different. There is no consistent way of testing. Instead, you have to spot the data pattern and code it up in Python, which sounds daunting at first but totally doable after practice.
In this post, I elaborate and live-code 5 real interview questions and help you better understand how math works in Python.
- Given two non-negative integers low and high. - Return the count of odd numbers between low and high (inclusive).- https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/
Microsoft asks this question. As a warm-up, this question appears to be too trivial to be included in data science or soft engineering interviews. However, it is deceivingly difficult if you don’t know the mathematical shortcut.
My first instinct is to iterate over the range of low and high bounds, inclusive, and count the number of odd numbers using a for loop.
The Python implementation works as follows.
3
As expected, it works well for a narrow range but super slow for a wide range. You can try this test case: countOdds(3,7222222222222222), which takes forever to complete.
As the featured theme of today’s blog post, we learn how to spot patterns in the data and use mathematic procedures to solve the questions at hand.
To calculate the odd numbers within the range of low and high, it is equal to the odd count up to the upper bound deducts by the odd number to the lower bound.
In math, the result = the count of odd until high — the count of odd until low.
Further, there are 50% odd, and 50% even numbers up to a number. For example, there are 4 odd and 4 even numbers for the range between 0 and 8.
The general Python implementation is as follows:
3611111111111110
The second approach returns the result instantly, even for a wide range. For questions that require math calculations, the priority is to analyze the pattern and find its mathematic equivalence. We have to practice a lot to be comfortable with the underlying thinking.
- You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.- Given n, find the total number of full staircase rows that can be formed.- n is a non-negative integer and fits within the range of a 32-bit signed integer.- https://leetcode.com/problems/arranging-coins/
Bloomberg includes this question. In total, there are n coins, and we try to put k number of coins in k-th row. I draw a simple diagram for visual aid.
If n = 8, and we put 1 on the first row, 2 on the second, 3 on the third, and 2 on the fourth. Since only the first three rows are full staircases, the function should return 3.
The interesting pattern is that there is a 1 unit increase from i-th full staircases to (i+1)th full staircases. In high school, we learned this type of sequence is called an arithmetic sequence or arithmetic progression. So, for the k-th complete staircase, the total number of coins = k*(k+1)/2.
Don’t worry if you can’t remember the formula. I Googled it while writing this post.
The next step is to find a way to maximize the number of complete staircases and minimize the distance between the coin count and n, which can be achieved using a binary search.
towardsdatascience.com
3
This is a standard implementation of a binary search, and the only catch is to be able to come up with the summation formula for an arithmetic sequence.
- A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).- Write a function to determine if a number is strobogrammatic. The number is represented as a string.- https://leetcode.com/problems/strobogrammatic-number/
Facebook asks this question. It would be helpful to write out some numbers and rotate them 180 degrees.
Original      180 degrees rotation   0                 0   1                 1   2              invalid   3              invalid   4              invalid   5              invalid   6                 9   7              invalid   8                 8   9                 6 
From 0 to 9, there are only 5 valid digits and 5 invalid digits after 180-degree rotation. For these valid digits, only 0, 1, and 8 stay the same after rotation, and the other two, 6 and 9, change values.
On the one hand, it would not be a valid number after rotations if the number contains any invalid digits.
On the other hand, we return the “mirrored” value for the valid digits (0, 1, 6, 8, and 9). We can create a dictionary and take advantage of its key-value pair feature to return the value.
Dictionary has a unique key-value pair feature, which comes in handy under a lot of scenarios. Take a look here:
towardsdatascience.com
In Python, we can do the following:
True
There are two catches. First, num is stored as a string, not an integer, and we have to be careful with accessing the string element. Second, digits change their positions after rotations, and so we have to use the reversed() method to read from the last (rightmost) digit backward, e.g., 169 → 691.
The rest is self-evident.
- The set S originally contains numbers from 1 to n. - But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.- Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.- https://leetcode.com/problems/set-mismatch/
Amazon asks this question. Simply puts, a number is repeated twice, and another number is missing in a sequence of numbers. Our job is to find them both.
It is possible to solve this question using non-math approaches, but the downside is the use of extra memory utilization, which may be prohibited in technical interviews. So, we will solve it using the mathematical approach.
#1 To find the repeated numberThe go-to data type is a set, which does not allow duplicates. By changing the data type to a set, we can get rid of the duplicated case. Then, take the difference between the total sum of the original array and the set. #2 To find the missing number Like the first step, we use a set to remove the duplicate and take the difference between the sum of the range up to n and the set.
In Python, we can do the following code.
[1, 2]
It works.
As a side note, combining a set with another function/method in Python, e.g., len() and sum(), is a powerful way of examining changes after taking out the replicates.
- Given an integer n, return true if it is a power of three. Otherwise, return false.- An integer n is a power of three, if there exists an integer x such that n == 3^x.- https://leetcode.com/problems/power-of-three/
Goldman Sachs and Hulu include this interview question. There are two approaches. First, we can use a while loop to divide the number by 3, and the remaining part should be 1 if it is a power of three. Second, we can use recursion. Here, I present both solutions for comparisons.
For this question, the math part is easy. We only have to keep in mind that the reminder should equal 1 for power numbers.
True
We need to specify the base condition for the second approach. For power numbers, the remaining part is equal to 0; for others, the remaining part isn’t 0.
False
The complete Python code is available on my Github.
Math can be handy for programming in Python.
The most challenging part is to spot the pattern and code it up.
To find patterns, writing out a few examples helps.
How about special cases? What to do for duplicates? A set can be helpful!
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
towardsdatascience.com
Please find me on LinkedIn and Youtube.
Also, check my other posts on Artificial Intelligence and Machine Learning.