General Coding Questions
Beginner Level Coding Questions
1. Reverse a String
python
def reverse_string(s):
return s[::-1]
# Example
print(reverse_string("livekit")) # Output: tikevil
2. Find the Maximum Number in a List
python
def max_in_list(lst):
return max(lst)
# Example
print(max_in_list([3, 1, 7, 4])) # Output: 7
3. Check if a Number is Prime
python
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Example
print(is_prime(17)) # Output: True
Intermediate Level Coding Questions
4. Merge Two Sorted Lists
python
def merge_sorted_lists(l1, l2):
result = []
i=j=0
while i < len(l1) and j < len(l2):
if l1[i] < l2[j]:
result.append(l1[i])
i += 1
else:
result.append(l2[j])
j += 1
result.extend(l1[i:])
result.extend(l2[j:])
return result
# Example
print(merge_sorted_lists([1,3,5],[2,4,6])) # Output: [1, 2, 3, 4, 5, 6]
5. Find the First Non-Repeating Character in a String
python
from collections import Counter
def first_non_repeating_char(s):
counts = Counter(s)
for char in s:
if counts[char] == 1:
return char
return None
# Example
print(first_non_repeating_char("livekitlive")) # Output: 'k'
6. Implement Fibonacci Sequence (Recursive and Iterative)
python
# Recursive
def fib_recursive(n):
if n <= 1:
return n
return fib_recursive(n-1) + fib_recursive(n-2)
# Iterative
def fib_iterative(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
# Example
print(fib_recursive(6)) # Output: 8
print(fib_iterative(6)) # Output: 8
Advanced Level Coding Questions
7. Find the Longest Substring Without Repeating Characters
python
def length_of_longest_substring(s):
char_index = {}
longest = start = 0
for i, char in enumerate(s):
if char in char_index and char_index[char] >= start:
start = char_index[char] + 1
char_index[char] = i
longest = max(longest, i - start + 1)
return longest
# Example
print(length_of_longest_substring("livekitai")) # Output: 6 ("vekita")
8. Detect Cycle in a Linked List (Floyd’s Cycle Detection)
python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
# Example construction skipped for brevity
9. Find Kth Largest Element in an Unsorted Array
python
import heapq
def find_kth_largest(nums, k):
return heapq.nlargest(k, nums)[-1]
# Example
print(find_kth_largest([3,2,1,5,6,4], 2)) # Output: 5
10. Implement a Basic LRU Cache
python
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key, value):
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
# Example
lru = LRUCache(2)
lru.put(1, 1)
lru.put(2, 2)
print(lru.get(1)) # Output: 1
lru.put(3, 3) # Evicts key 2
print(lru.get(2)) # Output: -1
Bonus: Data Science/ML Related Coding
11. Calculate Accuracy of Predictions
python
def accuracy(y_true, y_pred):
correct = sum(t==p for t, p in zip(y_true, y_pred))
return correct / len(y_true)
# Example
print(accuracy([1,0,1,1],[1,0,0,1])) # Output: 0.75
12. Simple Linear Regression (Using Least Squares)
python
def linear_regression(X, y):
n = len(X)
x_mean = sum(X) / n
y_mean = sum(y) / n
numerator = sum((X[i] - x_mean) * (y[i] - y_mean) for i in range(n))
denominator = sum((X[i] - x_mean)**2 for i in range(n))
slope = numerator / denominator
intercept = y_mean - slope * x_mean
return intercept, slope
# Example
X = [1, 2, 3, 4, 5]
y = [2, 4, 5, 4, 5]
print(linear_regression(X, y)) # Output: (2.2, 0.3)
AI & Data Science Questions with Code Snippet Answers
1. Difference between supervised and unsupervised learning
Conceptual; no code.
2. Basic steps in ML project
Conceptual; no code.
3. Types of ML algorithms
Conceptual; no code.
4. Handle missing data
python
import pandas as pd
df = pd.DataFrame({"A":[1,2,None,4]})
df['A'].fillna(df['A'].mean(), inplace=True) # Fill missing with mean
5. Overfitting prevention
Conceptual; code example with regularization on model below.
6. Bias-variance tradeoff
Conceptual; no code.
7. Precision, recall, F1 score
python
from sklearn.metrics import precision_score, recall_score, f1_score
y_true = [1,0,1,1]
y_pred = [1,0,0,1]
print(precision_score(y_true, y_pred))
print(recall_score(y_true, y_pred))
print(f1_score(y_true, y_pred))
8. Classification vs regression
Conceptual; no code.
9. Confusion matrix
python
from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_true, y_pred))
10. Python libraries for ML
No code.
11. Feature scaling
python
from sklearn.preprocessing import StandardScaler, MinMaxScaler
data = [[1], [2], [3]]
scaler = StandardScaler()
print(scaler.fit_transform(data))
12. L1 vs L2 regularization
Conceptual; L2 regularization example:
python
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(penalty='l2')
13. Cross-validation
python
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier
import numpy as np
X = np.random.rand(100,5)
y = np.random.randint(0,2,100)
model = RandomForestClassifier()
scores = cross_val_score(model, X, y, cv=5)
print(scores)
14. Decision trees and random forests
python
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=10)
model.fit(X, y)
15. Assumptions of linear regression
Conceptual.
16. ROC and AUC
python
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
y_score = model.predict_proba(X)[:,1]
fpr, tpr, _ = roc_curve(y, y_score)
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, label='AUC='+str(roc_auc))
plt.legend()
plt.show()
17. Dimensionality reduction (PCA)
python
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X)
print(X_reduced.shape)
18. Imbalanced data
Conceptual; example of oversampling:
python
from imblearn.over_sampling import SMOTE
smote = SMOTE()
X_res, y_res = smote.fit_resample(X, y)
19. Clustering (k-means)
python
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=3)
clusters = kmeans.fit_predict(X)
20. Hyperparameter tuning
python
from sklearn.model_selection import GridSearchCV
param_grid = {'n_estimators':[10, 50], 'max_depth':[None, 10]}
grid = GridSearchCV(RandomForestClassifier(), param_grid)
grid.fit(X, y)
print(grid.best_params_)
21. Neural networks basics
Conceptual
22. Backpropagation
Conceptual
23. CNN working
Example CNN model snippet:
python
import torch.nn as nn
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3)
self.pool = nn.MaxPool2d(2,2)
self.fc = nn.Linear(32*13*13, 10)
def forward(self, x):
x = self.pool(nn.functional.relu(self.conv1(x)))
x = x.view(-1, 32*13*13)
x = self.fc(x)
return x
24. RNN and limitations
Conceptual
25. Transformer architecture
Conceptual
26. Word embeddings (Word2Vec)
python
from gensim.models import Word2Vec
sentences = [['hello', 'world'], ['machine', 'learning']]
model = Word2Vec(sentences, vector_size=100, window=5, min_count=1)
print(model.wv['hello'])
27. Transfer learning snippet (PyTorch)
python
import torchvision.models as models
resnet = models.resnet18(pretrained=True)
for param in resnet.parameters():
param.requires_grad = False
resnet.fc = nn.Linear(resnet.fc.in_features, 2) # New output layer
28. Concept drift
Conceptual
29. Sequence-to-sequence models
Conceptual
30. GAN snippet - generator model example*
python
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
self.main = nn.Sequential(
nn.Linear(100, 256),
nn.ReLU(),
nn.Linear(256, 784),
nn.Tanh()
)
def forward(self, x):
return self.main(x)
31. Text preprocessing (tokenization & stopword removal)
python
import nltk
nltk.download('stopwords')
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
text = "This is an example."
tokens = word_tokenize(text.lower())
filtered = [w for w in tokens if w not in stop_words]
print(filtered)
32. Speech noise reduction
Conceptual
33. Metrics for speech-to-text
Conceptual — Word Error Rate (WER)
34. Real-time anomaly detection (stat example)
python
import numpy as np
data = np.random.normal(0, 1, 1000)
threshold = 3 * np.std(data)
anomalies = data[np.abs(data) > threshold]
print(anomalies)
35. Multimodal data integration
Conceptual
36. Time series forecasting (ARIMA example)
python
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
ts = pd.Series([1,2,3,4,5,6,7])
model = ARIMA(ts, order=(1,1,1))
model_fit = model.fit()
print(model_fit.forecast())
37. Reinforcement vs supervised learning
Conceptual
38. Deployment challenges
Conceptual
39. Model monitoring example (basic logging)
python
import logging
logging.basicConfig(filename='model.log', level=logging.INFO)
logging.info('Prediction made successfully')
40. Ethics in AI
Conceptual
41. Transformer models advances
Conceptual
42. Large language model text generation
python
from transformers import pipeline
generator = pipeline('text-generation', model='gpt2')
print(generator("LiveKit enables", max_length=20))
43. Generative AI risks
Conceptual
44. Self-supervised learning
Conceptual
45. Causal inference
Conceptual
46. Scaling multimodal AI
Conceptual
47. Improving voice agent AI
Conceptual
48. Explainability in AI
Conceptual
49. Real-time AI communication research trends
Conceptual
50. Designing adaptive AI systems
Conceptual