Member-only story

3 LeetCode One-Liners That Look Easy (But Can Make One P*ss Their Pants In A Tech Interview)

Dr. Ashish Bamania
6 min readApr 13, 2024

--

Generated with DALL-E 3

Here are 3 LeetCode one-liner array questions that look easy at first glance but are tricky enough to crash a tech interview.

#1: Convert A Non-negative Integer To Its English Word Representation

The question sounds simple but has a tricky solution.

Given a number (num), write a function that converts it into its corresponding English word representation (string).

For example, for 1234567, its English representation is One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven.

Let’s implement it.

We start with writing out a base case for zero.

if num == 0:
return "Zero"

Next, we create some predefined word lists that map numbers into words.

less_than_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", 
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",
"Eighteen", "Nineteen"]

tens = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]

thousands = ["", "Thousand", "Million", "Billion"]

After this, we define a helper function called words that helps us convert a number n that is less than 1000 into its word representation, recursively.

def words(n):
if n == 0:
return ""

elif n < 20:
return less_than_20[n] + " "

elif n < 100:
return tens[n//10] + " " + words(n % 10)

else:
return less_than_20[n // 100] + " Hundred " + words(n % 100)

Finally, we iterate through each group of 3 digits (thousands) in the given number and convert each group into words, appending the appropriate thousands unit.

result = ""

for i, thousand in enumerate(thousands):
if num == 0:
break

num, remainder = divmod(num, 1000)

if remainder…

--

--

Dr. Ashish Bamania
Dr. Ashish Bamania

Written by Dr. Ashish Bamania

🍰 I simplify the latest advances in AI, Quantum Computing & Software Engineering for you | 📰 Subscribe to my newsletter here: https://intoai.pub

Responses (1)