Understood — here are the answers/solutions to the 60 core Data Science coding
questions.
To keep this readable and usable, each solution is:
Short, clean, interview-ready
Pythonic
Using Pandas/NumPy where appropriate
Explained only where needed (no excessive text)
If you want full explanations or want these in a PDF, I can generate that too.
✅ SECTION 1 — Python Coding
Solutions
1. First non-repeating character
from collections import Counter
def first_unique(s):
freq = Counter(s)
for ch in s:
if freq[ch] == 1:
return ch
return None
2. Reverse words
def reverse_words(s):
return " ".join([Link]()[::-1])
3. Frequency of list items
from collections import Counter
Counter([1,2,2,3,3,3])
4. Flatten nested list
def flatten(lst):
out = []
for x in lst:
if isinstance(x, list):
[Link](flatten(x))
else:
[Link](x)
return out
5. Moving average
def moving_avg(arr, k):
return [sum(arr[i:i+k]) / k for i in range(len(arr)-k+1)]
6. Two-sum
def two_sum(nums, target):
seen = {}
for i, v in enumerate(nums):
if target - v in seen:
return (seen[target - v], i)
seen[v] = i
7. Longest substring without repeating chars
def longest_unique(s):
seen = {}
start = max_len = 0
for i, ch in enumerate(s):
if ch in seen and seen[ch] >= start:
start = seen[ch] + 1
seen[ch] = i
max_len = max(max_len, i - start + 1)
return max_len
8. Anagrams
def anagram(a, b):
return sorted([Link](" ","").lower()) == sorted([Link]("
","").lower())
9. Find duplicates
def find_duplicates(lst):
return [x for x, c in Counter(lst).items() if c > 1]
10. Merge sorted lists
def merge(a, b):
i=j=0; out=[]
while i<len(a) and j<len(b):
[Link](a[i] if a[i]<b[j] else b[j])
i+=a[i]<b[j]
j+=a[i]>=b[j]
return out + a[i:] + b[j:]
✅ SECTION 2 — Pandas
Solutions
Assume:
import pandas as pd
11. Drop missing
[Link]()
12. Fill NA per group
df['value'] = [Link]('group')['value'].transform(lambda x:
[Link]([Link]()))
13. Group by with stats
[Link]('category')['amount'].agg(['mean','sum','count'])
14. Pivot
[Link](index='id', columns='month', values='sales')
15. Melt
[Link](df, id_vars=['id'])
16. Merge on multiple keys
[Link](df1, df2, on=['id','date'], how='inner')
17. Row-wise apply
df['score'] = [Link](lambda r: r['a'] * r['b'], axis=1)
18. N largest per group
[Link]('group').apply(lambda x: [Link](3, 'value'))
19. Rolling mean
df['roll'] = df['value'].rolling(7).mean()
20. Detect outliers (IQR)
Q1 = df['x'].quantile(0.25)
Q3 = df['x'].quantile(0.75)
IQR = Q3 - Q1
outliers = df[(df['x'] < Q1 - 1.5*IQR) | (df['x'] > Q3 + 1.5*IQR)]
✅ SECTION 3 — NumPy
Solutions
import numpy as np
21. Matrix multiplication
[Link](A, B)
22. Remove zeros
arr[arr != 0]
23. Normalize 0–1
(x - [Link]()) / ([Link]() - [Link]())
24. Cosine similarity
def cosine(a, b):
return [Link](a, b) / ([Link](a)*[Link](b))
25. Softmax
def softmax(x):
e = [Link](x - [Link](x))
return e / [Link]()
✅ SECTION 4 — Data
Cleaning / Transformation
Solutions
26. Detect invalid rows
df[[Link](lambda r: any([
[Link](r[col]) for col in [Link]
]), axis=1)]
27. Convert timestamps & group
df['date'] = pd.to_datetime(df['timestamp'])
[Link](df['date'].[Link]).size()
28. Parse logs
df['status'] = df['log'].[Link](r'(\d{3})')
df['status'].value_counts()
29. Extract email domains
df['domain'] = df['email'].[Link]('@').str[1]
df['domain'].value_counts()
30. Convert categorical to dummies
pd.get_dummies(df, columns=['cat'])
✅ SECTION 5 — Probability /
Statistics Coding
31. Simulate biased coin
def biased_coin(p, n):
return [Link](n) < p
32. Monty Hall simulation
def monty(n=10000):
wins = 0
for _ in range(n):
car = [Link](3)
choice = [Link](3)
wins += (choice != car)
return wins / n
33. Bootstrap mean
def bootstrap_mean(x, B=1000):
return [[Link]([Link](x, len(x), True)) for _ in
range(B)]
34. KL divergence
def kl(p, q):
p, q = [Link](p), [Link](q)
return [Link](p * [Link](p / q))
35. Box–Muller normal sampling
def normal_sample(n):
u1, u2 = [Link](n), [Link](n)
z = [Link](-2*[Link](u1)) * [Link](2*[Link]*u2)
return z
✅ SECTION 6 — ML
Algorithms from Scratch
36. Linear regression (gradient descent)
def linreg(X, y, lr=0.01, it=1000):
m, b = 0, 0
n = len(y)
for _ in range(it):
pred = m*X + b
m -= lr * (-2/n) * [Link](X*(y-pred))
b -= lr * (-2/n) * [Link](y-pred)
return m, b
37. Logistic regression
def sigmoid(x): return 1/(1+[Link](-x))
def logreg(X, y, lr=0.1, it=1000):
w = [Link]([Link][1])
for _ in range(it):
pred = sigmoid(X@w)
w -= lr * (X.T @ (pred - y)) / len(y)
return w
38. K-means
def kmeans(X, k, it=100):
cent = X[[Link](len(X), k)]
for _ in range(it):
labels = [Link](((X[:,None]-cent)**2).sum(axis=2), axis=1)
cent = [Link]([X[labels==i].mean(axis=0) for i in
range(k)])
return labels, cent
39. PCA (SVD)
def pca(X):
Xc = X - [Link](axis=0)
U, S, Vt = [Link](Xc, full_matrices=False)
return Vt # principal components
40. Naive Bayes
class NB:
def fit(self, X, y):
[Link] = [Link](y)
[Link] = [Link](y).mean()
[Link] = [Link](y).var()
[Link] = y.value_counts()/len(y)
def predict(self, x):
probs = {}
for c in [Link]:
m, v = [Link][c], [Link][c]
p = -0.5*[Link]([Link](2*[Link]*v) + (x-m)**2 / (2*v))
probs[c] = p + [Link]([Link][c])
return max(probs, key=[Link])
41. Decision tree entropy
def entropy(y):
p = [Link](y) / len(y)
return -[Link](p[p>0] * np.log2(p[p>0]))
42. KNN
def knn(X, y, x, k=3):
d = [Link](X - x, axis=1)
idx = [Link]()[:k]
return [Link](y[idx]).argmax()
✅ SECTION 7 — DS Case Tasks
43. Detect anomalies (z-score)
z = (df['x'] - df['x'].mean()) / df['x'].std()
df[[Link]() > 3]
44. User summary
[Link]('user')['amount'].agg(['sum','mean','count'])
45. Recommendation score
from [Link] import cosine_similarity
cosine_similarity(user_vec.reshape(1,-1), item_vecs)
46. Churn detection
df['last_date'] = [Link]('user')['date'].transform(max)
churned = df[df['last_date'] < df['date'].max() -
[Link](days=30)]
47. Cohorts
df['cohort'] = [Link]('user')['date'].transform('min')
cohorts = [Link]([df['cohort'].dt.to_period('M'),
df['date'].dt.to_period('M')]).size()
48. Lag features
df['lag1'] = df['value'].shift(1)
df['lag7'] = df['value'].shift(7)
49. KPIs
df['amount'].sum()
df['user'].nunique()
[Link]('category')['amount'].sum()
50. Most common sequences
df['next'] = [Link]('user')['event'].shift(-1)
[Link](['event','next']).size().nlargest(10)
✅ SECTION 8 — Algorithms for
DS
51. Sliding window max
from collections import deque
def slide_max(nums, k):
d = deque()
out = []
for i,n in enumerate(nums):
while d and nums[d[-1]] <= n: [Link]()
[Link](i)
if d[0] == i-k: [Link]()
if i >= k-1: [Link](nums[d[0]])
return out
52. Histogram
def histogram(arr):
return Counter(arr)
53. Reservoir sampling
def reservoir(stream, k):
import random
res = stream[:k]
for i in range(k, len(stream)):
j = [Link](0, i)
if j < k:
res[j] = stream[i]
return res
54. Fisher–Yates shuffle
def shuffle(arr):
import random
for i in range(len(arr)-1,0,-1):
j = [Link](0,i)
arr[i], arr[j] = arr[j], arr[i]
return arr
55. Simple hashmap
class HashMap:
def __init__(self): self.t = {}
def put(self,k,v): self.t[k]=v
def get(self,k): return [Link](k)
SECTION 9 — SQL-to-Python
56. GROUP BY
{key: sum(g) for key, g in groupby(sorted(data), key=lambda x: x[0])}
57. JOIN
def join(a, b, key):
bmap = {row[key]: row for row in b}
return [{**row, **bmap[row[key]]} for row in a if row[key] in
bmap]
58. Windowed rank
df['rank'] = [Link]('group')['value'].rank(method='dense',
ascending=False)
SECTION 10 — Visualization
59. Plot distribution
import [Link] as plt
[Link](data, bins=30)
[Link]()
60. Correlation heatmap
[Link]([Link](), cmap='viridis')
[Link]()
[Link]()
✅ Done — all 60 answers
provided.
If you'd like:
✔ I can package these into a PDF
✔ I can give you practice tests
✔ I can run a mock interview
✔ I can provide explanations for each solution
Just tell me what you want next.