Skip to content
KPHB Colony, Kukatpally, Hyderabad Mon–Sat · 9 AM – 9 PM +91 96664 47822 Free demo class — book your seat

Free interview prep

Data Science & AI interview questions — with answers

350 questions that come up in data analyst, data scientist and AI engineer interviews, with short model answers. Written by The Data School team in KPHB, Hyderabad.

01

Python interview questions

Core Python questions asked in data analyst, data scientist and AI engineer interviews — data types, functions, OOP, generators, performance and NumPy. 50 questions

Q1

What is the difference between a list and a tuple in Python?

Lists are mutable — you can add, remove or change items — and use square brackets. Tuples are immutable and use parentheses. Because tuples can't change, they are hashable (if their items are) and can be used as dictionary keys, and they are slightly faster and lighter in memory.

Q2

What are *args and **kwargs?

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary. They let a function accept a variable number of inputs, and are common in wrappers and decorators that pass arguments through to another function.

Q3

Explain list comprehension with an example.

A list comprehension builds a list in one readable expression: [x * x for x in nums if x % 2 == 0] returns the squares of the even numbers in nums. It is usually faster and clearer than an equivalent for-loop with append().

Q4

What is the difference between a shallow copy and a deep copy?

A shallow copy (copy.copy or list.copy) creates a new outer object but keeps references to the same inner objects, so changing a nested list affects both. A deep copy (copy.deepcopy) recursively copies every nested object, so the two are fully independent.

Q5

What is a Python decorator?

A decorator is a function that takes another function and returns a new function that adds behaviour before or after it runs — for example logging, timing, caching or access checks. It is applied with the @decorator syntax above the function definition.

Q6

What is a generator and why use one?

A generator is a function that uses yield to produce values one at a time instead of building the whole result in memory. It is ideal for large files or streams: you can iterate over millions of rows while holding only one in memory.

Q7

How is == different from is?

== compares values (do the two objects have equal contents?), while is compares identity (are they the same object in memory?). Use is only for singletons such as None: if x is None.

Q8

How do you handle exceptions in Python?

Wrap risky code in try, catch specific errors with except ValueError: (avoid bare except), use else for code that runs only when no error occurred, and finally for clean-up that must always run, such as closing a file or connection.

Q9

What are Python's built-in data types?

Numbers (int, float, complex), bool, str, and the collections list, tuple, set, frozenset and dict, plus bytes, bytearray and NoneType. Knowing which are mutable (list, set, dict, bytearray) and which are immutable (int, str, tuple, frozenset) is a common follow-up.

Q10

What is the difference between mutable and immutable objects?

Mutable objects can be changed in place after creation (lists, dicts, sets). Immutable objects cannot; any 'change' creates a new object (ints, strings, tuples). This matters for function arguments, default values and dictionary keys, which must be immutable/hashable.

Q11

Why is using a mutable default argument a bug?

Default values are evaluated once, when the function is defined. def add(item, items=[]) reuses the same list on every call, so items accumulate across calls. Use items=None and create a new list inside the function instead.

Q12

What is a dictionary and how does lookup work?

A dict stores key-value pairs in a hash table. Python hashes the key to find its slot, so lookups, inserts and deletes are O(1) on average. Keys must be hashable; since Python 3.7 dicts keep insertion order.

Q13

What is the difference between a set and a list?

A set holds unique, unordered, hashable items and checks membership in O(1) on average; a list is ordered, allows duplicates and checks membership in O(n). Use a set to remove duplicates or test 'is x in this collection?' quickly.

Q14

What are lambda functions?

A lambda is a small anonymous function written in one expression: lambda x: x * 2. They are handy as short arguments to sorted(key=...), map(), filter() or Pandas apply(), but named functions are clearer for anything non-trivial.

Q15

Explain map(), filter() and reduce().

map(f, items) applies f to every item; filter(f, items) keeps items where f returns True; functools.reduce(f, items) combines items into one value, such as a running product. In modern Python, comprehensions often replace map and filter for readability.

Q16

What does the with statement do?

with uses a context manager to set up and reliably tear down a resource. with open('data.csv') as f: guarantees the file is closed even if an error occurs. You can write your own context managers with __enter__/__exit__ or contextlib.contextmanager.

Q17

What is the Global Interpreter Lock (GIL)?

In CPython, the GIL allows only one thread to execute Python bytecode at a time. Threads still help for I/O-bound work (network, disk), but CPU-bound work needs multiprocessing, native libraries like NumPy that release the GIL, or other approaches.

Q18

Multithreading vs multiprocessing — when do you use each?

Use threads (or asyncio) for I/O-bound tasks such as calling many APIs, because the GIL is released while waiting. Use multiprocessing for CPU-bound tasks such as heavy computation, because each process has its own interpreter and GIL.

Q19

What is asyncio?

asyncio is Python's library for asynchronous, single-threaded concurrency using async def and await. While one task waits on I/O, the event loop runs others. It is efficient for many concurrent network calls, such as hitting several LLM or web APIs at once.

Q20

What are classes and objects?

A class is a blueprint that defines attributes and methods; an object is an instance of that class. __init__ initialises a new object's attributes, and self refers to the instance the method is called on.

Q21

Explain the four pillars of OOP in Python.

Encapsulation bundles data and behaviour and hides internals; inheritance lets a class reuse another's behaviour; polymorphism lets different classes share an interface (e.g. each has a .predict()); abstraction exposes what an object does while hiding how.

Q22

What is the difference between @staticmethod and @classmethod?

A staticmethod takes no automatic first argument — it's a plain function grouped in the class. A classmethod receives the class (cls) as its first argument and is often used for alternative constructors, such as Model.from_config(cfg).

Q23

What are dunder (magic) methods?

Methods with double underscores, like __init__, __str__, __repr__, __len__, __eq__ and __add__, let your objects work with built-in syntax and functions — printing, len(), comparisons and operators.

Q24

What is the difference between __str__ and __repr__?

__str__ returns a readable, user-friendly string used by print(). __repr__ returns an unambiguous developer-facing string, ideally one that could recreate the object, used in the REPL and debugging. If __str__ is missing, Python falls back to __repr__.

Q25

What is inheritance and what does super() do?

Inheritance lets a child class reuse and extend a parent class. super() calls the parent's method — commonly super().__init__(...) inside the child's __init__ — so the parent's setup still runs. Python resolves methods using the MRO (method resolution order).

Q26

What is the difference between an iterable and an iterator?

An iterable is anything you can loop over (lists, strings, dicts) because it has __iter__. An iterator is the object that produces the values one by one with __next__ and remembers its position. iter(iterable) returns an iterator.

Q27

What does the yield keyword do?

yield turns a function into a generator: it returns a value, pauses the function and keeps its local state, then resumes from the same point on the next request. This produces values lazily without building a full list.

Q28

What are generator expressions?

Like list comprehensions but with parentheses: sum(x * x for x in range(10**6)). They yield items lazily instead of creating a full list, which saves memory when you only need to iterate once.

Q29

How do you read a large CSV file without running out of memory?

Process it in pieces: pd.read_csv(path, chunksize=100_000) returns chunks you can aggregate one at a time, or read only the columns you need with usecols and efficient dtypes. Python's csv module with a loop also streams row by row.

Q30

What is the difference between append() and extend()?

append(x) adds x as a single element — appending a list adds a nested list. extend(iterable) adds each element of the iterable individually. [1,2].append([3,4]) gives [1,2,[3,4]]; extend gives [1,2,3,4].

Q31

How do you remove duplicates from a list while keeping order?

Use list(dict.fromkeys(items)) — dict keys are unique and preserve insertion order. list(set(items)) also removes duplicates but loses the original order.

Q32

How do you reverse a string or list?

Use slicing with a negative step: text[::-1]. For lists you can also call items.reverse() to reverse in place, or reversed(items) for an iterator.

Q33

What is slicing?

Slicing extracts part of a sequence with seq[start:stop:step]; start is included, stop is excluded. nums[1:4] gives items 1–3, nums[-3:] the last three, nums[::2] every second item. Slicing a list returns a new list.

Q34

What are f-strings?

Formatted string literals introduced in Python 3.6: f"Revenue: {total:,.2f}". They embed expressions directly inside strings, support format specifiers, and are faster and more readable than % formatting or .format().

Q35

What is the difference between sort() and sorted()?

list.sort() sorts the list in place and returns None. sorted(iterable) returns a new sorted list and works on any iterable. Both accept key= and reverse=, e.g. sorted(people, key=lambda p: p['age']).

Q36

How does Python manage memory?

CPython uses reference counting — objects are freed when no references remain — plus a cyclic garbage collector that finds groups of objects referencing each other. Memory comes from a private heap managed by the interpreter.

Q37

What is a virtual environment and why use one?

A virtual environment (venv, conda) is an isolated Python installation with its own packages. It keeps each project's dependency versions separate, avoids conflicts, and makes environments reproducible with requirements.txt or environment files.

Q38

What is the difference between a module and a package?

A module is a single .py file. A package is a directory of modules (traditionally with an __init__.py) that can be imported with dotted names, like sklearn.model_selection.

Q39

What does if __name__ == "__main__": mean?

When a file runs directly, its __name__ is "__main__"; when it's imported, __name__ is the module name. Code under this check runs only when the file is executed as a script, not on import — useful for tests or a main() entry point.

Q40

What are type hints?

Optional annotations such as def mean(xs: list[float]) -> float. Python doesn't enforce them at runtime, but they improve readability, editor autocomplete and let tools like mypy catch type errors before you run the code.

Q41

What is a closure?

A closure is an inner function that remembers variables from its enclosing function even after the outer function has returned. Closures power decorators and function factories such as make_multiplier(3) returning a function that triples its input.

Q42

Explain the LEGB scope rule.

Python looks up names in this order: Local (inside the current function), Enclosing (outer functions), Global (module level) and Built-in. Use global or nonlocal only when you deliberately need to rebind an outer variable.

Q43

What is pickling?

Pickling serialises a Python object into bytes with the pickle module so it can be saved or sent and later restored (unpickling). It's often used to save trained models. Never unpickle data from untrusted sources — it can execute code.

Q44

How do you work with JSON in Python?

Use the json module: json.loads() parses a JSON string into dicts and lists, json.dumps() converts Python objects to a JSON string, and json.load()/json.dump() work with files. requests responses also offer .json().

Q45

How do you call a REST API in Python?

Use the requests library: r = requests.get(url, params=..., headers=..., timeout=10), then r.raise_for_status() and data = r.json(). For POST requests send json=payload. Always set timeouts and handle errors and rate limits.

Q46

What is the zip() function?

zip() pairs items from several iterables position by position: list(zip(names, scores)) gives [(name1, score1), ...]. It stops at the shortest input. dict(zip(keys, values)) is a quick way to build a dictionary.

Q47

What does enumerate() do?

enumerate(items, start=0) yields (index, item) pairs, so you can loop with an index without managing a counter: for i, row in enumerate(rows, start=1):

Q48

What is NumPy broadcasting?

Broadcasting lets NumPy perform arithmetic on arrays of different shapes by virtually stretching the smaller one, without copying data. For example, subtracting a row of column means from a 2D array centres every column in one vectorised step.

Q49

Why are NumPy arrays faster than Python lists?

NumPy arrays store items of one type in contiguous memory and run operations in optimised C code (vectorisation), avoiding Python's per-element overhead. Lists store references to separate Python objects of any type.

Q50

How do you find and fix a slow Python script?

Measure first with time, timeit or cProfile to find the hot spots. Then vectorise with NumPy/Pandas instead of loops, use the right data structure (sets/dicts for lookups), cache repeated work with functools.lru_cache, and parallelise I/O-bound tasks.

02

SQL interview questions

SQL is tested in almost every data role. Expect joins, aggregation, window functions, indexing, normalisation and classic query problems. 50 questions

Q1

What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping; HAVING filters groups after GROUP BY and can use aggregates. Example: WHERE city = 'Hyderabad' … GROUP BY course HAVING COUNT(*) > 10.

Q2

Explain INNER, LEFT, RIGHT and FULL OUTER JOIN.

INNER JOIN returns only rows with a match in both tables. LEFT JOIN returns all rows from the left table plus matches from the right (NULLs where there is no match); RIGHT JOIN is the mirror image. FULL OUTER JOIN returns all rows from both tables, matched where possible.

Q3

What is the difference between RANK, DENSE_RANK and ROW_NUMBER?

All three are window functions. ROW_NUMBER gives a unique sequence (1, 2, 3, 4) even for ties. RANK gives ties the same rank and then skips (1, 2, 2, 4). DENSE_RANK gives ties the same rank without gaps (1, 2, 2, 3).

Q4

How do you find the second-highest salary in a table?

One clean approach: SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS r FROM employees) t WHERE r = 2. DENSE_RANK handles duplicate top salaries correctly. An alternative is SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees).

Q5

What is a CTE and when would you use one?

A Common Table Expression (WITH name AS (…)) is a named, temporary result you can reference in the main query. It makes multi-step logic readable, can be referenced more than once, and recursive CTEs can walk hierarchies such as an org chart.

Q6

What is the difference between UNION and UNION ALL?

UNION combines results and removes duplicates, which needs an extra sort or hash step. UNION ALL keeps every row including duplicates and is faster. Use UNION ALL unless you specifically need de-duplication.

Q7

What are primary keys and foreign keys?

A primary key uniquely identifies each row and cannot be NULL. A foreign key is a column that references the primary key of another table, enforcing referential integrity — for example, every enrolment row must point to an existing student.

Q8

How would you speed up a slow query?

Check the execution plan (EXPLAIN), add indexes on columns used in joins, WHERE and ORDER BY, select only the columns you need instead of SELECT *, filter early, avoid functions on indexed columns in WHERE, and pre-aggregate large tables where it makes sense.

Q9

What is the logical order in which SQL clauses are executed?

FROM and JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT/OFFSET. That's why you can't use a SELECT alias in WHERE, but you usually can in ORDER BY.

Q10

What is the difference between DELETE, TRUNCATE and DROP?

DELETE removes selected rows (with WHERE) and can be rolled back in a transaction. TRUNCATE quickly removes all rows but keeps the table structure. DROP removes the table itself, including its structure and data.

Q11

What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?

COUNT(*) counts all rows. COUNT(column) counts rows where that column is not NULL. COUNT(DISTINCT column) counts unique non-NULL values.

Q12

How does NULL behave in SQL?

NULL means unknown, so comparisons with = or <> return unknown, not true. Use IS NULL / IS NOT NULL. Aggregates such as SUM and AVG ignore NULLs, and COALESCE(col, 0) replaces NULL with a default.

Q13

What does COALESCE do?

COALESCE returns the first non-NULL value from its arguments: COALESCE(phone, mobile, 'Not provided'). It's commonly used to fill missing values in reports or before calculations.

Q14

How do you find duplicate records?

Group by the columns that define a duplicate and keep groups with more than one row: SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1.

Q15

How do you delete duplicates but keep one row?

Number the rows within each duplicate group and delete the extras: WITH d AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn FROM users) DELETE FROM users WHERE id IN (SELECT id FROM d WHERE rn > 1).

Q16

What is a self join? Give an example.

A self join joins a table to itself using aliases. Classic example — list each employee with their manager: SELECT e.name, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id.

Q17

What is a CROSS JOIN?

A CROSS JOIN returns the Cartesian product — every row of one table combined with every row of the other. It's useful for generating combinations, such as every store × every date, but can explode in size if used by accident.

Q18

What is a subquery, and what is a correlated subquery?

A subquery is a query nested inside another. A correlated subquery references columns from the outer query and runs once per outer row, e.g. employees earning more than their department's average. They can often be rewritten as joins or window functions for speed.

Q19

IN vs EXISTS — what's the difference?

IN checks whether a value is in a list or subquery result; EXISTS checks whether a subquery returns any row. EXISTS stops at the first match and handles NULLs more predictably, so it's often preferred for correlated checks. Beware NOT IN with NULLs, which can return no rows.

Q20

What are window functions?

Window functions compute a value for each row using a set of related rows, without collapsing them like GROUP BY. They use OVER (PARTITION BY … ORDER BY …) — for example running totals, rankings, moving averages and comparing each row to the previous one.

Q21

How do you calculate a running total?

Use SUM as a window function: SELECT order_date, amount, SUM(amount) OVER (ORDER BY order_date) AS running_total FROM orders. Add PARTITION BY customer_id for a running total per customer.

Q22

What do LAG and LEAD do?

LAG(col) returns the value from a previous row and LEAD(col) from a following row in the window order. They're used for month-over-month change: revenue - LAG(revenue) OVER (ORDER BY month).

Q23

How do you get the top N rows per group?

Rank inside each group and filter: WITH r AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) AS rn FROM products) SELECT * FROM r WHERE rn <= 3.

Q24

How do you calculate a 7-day moving average?

Use a window frame: AVG(sales) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW). This averages the current row and the six before it.

Q25

What is an index and how does it help?

An index is a separate data structure (usually a B-tree) that lets the database find rows without scanning the whole table, much like a book index. It speeds up reads on filtered, joined and sorted columns but slows writes and uses storage.

Q26

Clustered vs non-clustered index?

A clustered index defines the physical order of rows in the table, so there can be only one (often the primary key). A non-clustered index is a separate structure pointing to the rows; a table can have many.

Q27

When can an index hurt performance?

Too many indexes slow down INSERT, UPDATE and DELETE because each index must be updated. Indexes on low-selectivity columns (like a yes/no flag) rarely help, and functions on indexed columns in WHERE can stop the index being used.

Q28

What is normalisation?

Normalisation organises tables to reduce redundancy and update anomalies by splitting data into related tables. 1NF: atomic values, no repeating groups. 2NF: no partial dependency on part of a composite key. 3NF: no transitive dependency between non-key columns.

Q29

What is denormalisation and when is it used?

Denormalisation deliberately adds redundancy — for example storing customer city on the orders table — to make reads faster and simpler. It's common in data warehouses and reporting, at the cost of more storage and harder updates.

Q30

OLTP vs OLAP?

OLTP systems handle many small, fast transactions such as orders and payments, with normalised tables. OLAP systems support analysis over large historical data, usually with denormalised star schemas in a data warehouse.

Q31

What is a star schema?

A warehouse design with a central fact table of measurable events (sales amount, quantity) and foreign keys to surrounding dimension tables (date, product, customer, store). It keeps analytical queries simple and fast.

Q32

What is a view? How is a materialised view different?

A view is a saved query that behaves like a virtual table; it runs each time you query it. A materialised view stores the query result physically, so it's faster to read but must be refreshed to stay current.

Q33

What is a stored procedure?

A stored procedure is a named block of SQL (and procedural logic) saved in the database and executed with a call. It can take parameters, run multiple statements and encapsulate business logic close to the data.

Q34

What are ACID properties?

Atomicity (all or nothing), Consistency (the database moves from one valid state to another), Isolation (concurrent transactions don't interfere) and Durability (committed changes survive crashes). They make transactions reliable.

Q35

What is a transaction?

A transaction groups statements into one unit of work: BEGIN, run the statements, then COMMIT to save or ROLLBACK to undo. The classic example is a bank transfer — debit and credit must both succeed or both fail.

Q36

What are constraints in SQL?

Rules enforced by the database: PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK (e.g. price > 0) and DEFAULT. They protect data quality at the source.

Q37

CHAR vs VARCHAR?

CHAR(n) stores fixed-length strings padded with spaces; VARCHAR(n) stores variable-length strings up to n characters. Use CHAR for fixed codes like country codes, VARCHAR for most text.

Q38

How do you write conditional logic in SQL?

Use CASE: CASE WHEN score >= 90 THEN 'A' WHEN score >= 75 THEN 'B' ELSE 'C' END AS grade. CASE also enables conditional aggregation such as SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END).

Q39

How do you pivot rows into columns?

Use conditional aggregation, which works everywhere: SELECT product, SUM(CASE WHEN month = 'Jan' THEN sales END) AS jan, SUM(CASE WHEN month = 'Feb' THEN sales END) AS feb FROM sales GROUP BY product. Some databases also offer PIVOT.

Q40

How do you work with dates in SQL?

Use the database's date functions to extract parts (EXTRACT or DATE_PART), truncate to a period (DATE_TRUNC('month', order_date)), add intervals and compute differences. Grouping by DATE_TRUNC is the standard way to build monthly reports.

Q41

How do you calculate month-over-month growth?

Aggregate by month, then compare with the previous month using LAG: (revenue - LAG(revenue) OVER (ORDER BY month)) * 100.0 / LAG(revenue) OVER (ORDER BY month). Watch out for division by zero and integer division.

Q42

How do you find customers who made no orders?

Use a LEFT JOIN and keep unmatched rows: SELECT c.* FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL. NOT EXISTS is an equally good alternative.

Q43

What is the difference between a JOIN and a UNION?

A JOIN combines columns from tables side by side based on a matching condition. A UNION stacks the rows of two queries with the same number and type of columns on top of each other.

Q44

What does DISTINCT do and what's a cheaper alternative?

DISTINCT removes duplicate rows from the result, which requires sorting or hashing. If duplicates come from a join, fixing the join or using EXISTS is often faster and more correct than adding DISTINCT.

Q45

How do you paginate results?

LIMIT/OFFSET (or OFFSET … FETCH) works for small pages, but large offsets get slow because skipped rows are still read. Keyset pagination — WHERE id > last_seen_id ORDER BY id LIMIT 20 — stays fast on big tables.

Q46

What is SQL injection and how do you prevent it?

SQL injection happens when user input is concatenated into a query and changes its meaning. Prevent it with parameterised queries (placeholders), ORMs or query builders, input validation, and least-privilege database accounts.

Q47

What is a recursive CTE used for?

Recursive CTEs repeatedly join a query to its own result to walk hierarchical or graph data — org charts, category trees, bill of materials — or to generate number and date series.

Q48

How do you find the median in SQL?

Many databases support PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary). Without it, rank rows with ROW_NUMBER and COUNT and average the middle one or two values.

Q49

What is the difference between GROUP BY and PARTITION BY?

GROUP BY collapses rows into one row per group. PARTITION BY (inside OVER) divides rows into groups for a window function but keeps every row, so you can show each row alongside its group total or rank.

Q50

How do you approach a SQL interview question you haven't seen before?

Clarify the tables, grain and expected output; write the result columns first; build the query step by step with CTEs; handle NULLs, duplicates and ties explicitly; and test the logic on a few sample rows out loud.

03

Statistics & Probability interview questions

The statistics behind experiments, sampling and model evaluation — hypothesis tests, distributions, A/B testing and Bayes. 50 questions

Q1

What is a p-value?

The p-value is the probability of seeing results at least as extreme as the observed data if the null hypothesis were true. A small p-value (commonly below 0.05) suggests the data is unlikely under the null, so we reject it. It is not the probability that the null hypothesis is true.

Q2

Explain Type I and Type II errors.

A Type I error is a false positive — rejecting a true null hypothesis (its rate is α). A Type II error is a false negative — failing to reject a false null (its rate is β; power = 1 − β). Lowering one usually raises the other unless you collect more data.

Q3

What is the Central Limit Theorem?

For a large enough sample, the distribution of the sample mean is approximately normal, whatever the shape of the population distribution (given finite variance). This is why confidence intervals and many hypothesis tests work on real-world, non-normal data.

Q4

What is the difference between mean, median and mode — and when do you use the median?

The mean is the average, the median is the middle value and the mode is the most frequent value. Use the median when data is skewed or has outliers, such as income or house prices, because a few extreme values pull the mean but barely move the median.

Q5

Correlation vs causation — what's the difference?

Correlation means two variables move together; causation means one actually changes the other. A correlation can come from a confounding variable or coincidence. To show causation you need a controlled experiment such as an A/B test, or careful causal-inference methods.

Q6

How would you design an A/B test?

Define one primary metric and a hypothesis, calculate the sample size needed for the effect you care about, randomly assign users to control and variant, run for a fixed period (don't stop early when it looks good), then test for significance and check guardrail metrics before rolling out.

Q7

What is the difference between a population and a sample?

The population is the whole group you care about (all customers); a sample is the subset you actually observe. Statistics estimate population parameters from sample data, so how the sample is drawn matters as much as its size.

Q8

What is variance and standard deviation?

Variance is the average squared distance of values from the mean; standard deviation is its square root, expressed in the same units as the data. Both measure spread — a larger standard deviation means values are more scattered.

Q9

What is a normal distribution?

A symmetric, bell-shaped distribution described by its mean and standard deviation. About 68% of values fall within 1 SD of the mean, 95% within 2 SD and 99.7% within 3 SD (the empirical rule).

Q10

What is a z-score?

A z-score tells you how many standard deviations a value is from the mean: z = (x − mean) / SD. It standardises values from different scales and helps flag outliers, often those beyond ±3.

Q11

What is skewness?

Skewness measures asymmetry. In a right-skewed (positive) distribution, like income, the long tail is on the right and the mean is greater than the median. In a left-skewed distribution the tail is on the left and the mean is below the median.

Q12

What is kurtosis?

Kurtosis describes how heavy a distribution's tails are compared with a normal distribution. High kurtosis means more extreme values (fat tails), which matters in areas like finance and risk.

Q13

What is a confidence interval?

A range calculated from sample data that would contain the true parameter in a stated share of repeated samples — for a 95% CI, about 95 out of 100 such intervals. Wider intervals mean more uncertainty; larger samples make them narrower.

Q14

What is the null hypothesis?

The default assumption of no effect or no difference — for example, 'the new checkout page does not change conversion rate'. A hypothesis test asks whether the data gives enough evidence to reject it in favour of the alternative hypothesis.

Q15

One-tailed vs two-tailed test?

A two-tailed test checks for a difference in either direction; a one-tailed test checks only one direction (e.g. 'B is better than A'). Two-tailed is the safer default unless a direction was justified before seeing the data.

Q16

What is statistical power?

Power is the probability that a test detects a real effect of a given size (1 − β). It increases with larger samples, larger true effects, lower variance and a higher α. Experiments are usually designed for 80% power.

Q17

What is a t-test and when do you use it?

A t-test compares means. A one-sample t-test compares a mean to a value; an independent two-sample test compares two groups; a paired test compares before-and-after measurements on the same subjects. It's used when population SD is unknown.

Q18

When do you use a chi-square test?

To test relationships between categorical variables — for example whether course choice is independent of city — using a contingency table of counts, or to check whether observed counts fit an expected distribution.

Q19

What is ANOVA?

Analysis of variance tests whether the means of three or more groups differ, by comparing variation between groups with variation within groups. A significant result says at least one mean differs; post-hoc tests show which.

Q20

What is the law of large numbers?

As sample size grows, the sample mean gets closer to the true population mean. It's why averages from large samples are reliable and why casinos win in the long run.

Q21

What is Bayes' theorem?

It updates the probability of a hypothesis given new evidence: P(A|B) = P(B|A) × P(A) / P(B). It's the basis of spam filters, medical test interpretation and Naive Bayes classifiers.

Q22

A test is 99% accurate for a disease that affects 1 in 1,000 people. If you test positive, how likely are you to have it?

Much lower than 99%. In 100,000 people, about 100 have the disease and ~99 test positive, while ~999 of the 99,900 healthy people also test positive. So only about 99 / 1,098 ≈ 9% of positives are real — the base rate matters.

Q23

What is conditional probability?

The probability of an event given that another has occurred: P(A|B) = P(A and B) / P(B). For example, the probability a user buys given they added an item to the cart.

Q24

What are independent events?

Events where one doesn't change the probability of the other: P(A and B) = P(A) × P(B). Coin tosses are independent; drawing cards without replacement is not.

Q25

What is the binomial distribution?

It models the number of successes in n independent trials with the same success probability p — for example how many of 20 leads convert if each converts with probability 0.1.

Q26

What is the Poisson distribution?

It models the count of events in a fixed interval when events occur independently at a constant average rate — calls per hour, website errors per day. Its mean and variance are both λ.

Q27

What is sampling bias? Give examples.

When the sample doesn't represent the population. Examples: surveying only app users about app satisfaction, survivorship bias (studying only successful companies), and self-selection in voluntary reviews.

Q28

What sampling methods do you know?

Simple random sampling, stratified sampling (sample within groups such as cities), cluster sampling (sample whole groups), systematic sampling (every k-th record) and convenience sampling, which is easy but often biased.

Q29

How do you detect outliers?

Visually with box plots and scatter plots, and statistically with z-scores (|z| > 3) or the IQR rule — values below Q1 − 1.5×IQR or above Q3 + 1.5×IQR. Always investigate before removing: an outlier may be an error or the most important data point.

Q30

What is the interquartile range (IQR)?

The range of the middle 50% of the data: IQR = Q3 − Q1. It's robust to outliers and is the basis of the box plot.

Q31

What is covariance vs correlation?

Both measure how two variables move together. Covariance depends on units, so its size is hard to interpret. Correlation (Pearson's r) is standardised between −1 and 1, making strength and direction easy to compare.

Q32

Pearson vs Spearman correlation?

Pearson measures linear relationships between continuous variables and is sensitive to outliers. Spearman uses ranks, so it captures monotonic (consistently increasing or decreasing) relationships and is more robust.

Q33

What is multicollinearity and why does it matter?

When predictors are highly correlated with each other. It makes regression coefficients unstable and hard to interpret, though predictions may still be fine. Detect it with correlation matrices or VIF; fix it by dropping or combining features or using regularisation.

Q34

What is linear regression and its assumptions?

It models a target as a linear combination of predictors. Key assumptions: linear relationship, independent errors, constant error variance (homoscedasticity), normally distributed errors for inference, and no severe multicollinearity.

Q35

What does R-squared mean?

R² is the share of variance in the target explained by the model, from 0 to 1. It always rises when you add features, so adjusted R² — which penalises extra predictors — is better for comparing models.

Q36

What is the multiple testing problem?

Running many tests inflates false positives: at α = 0.05, about 1 in 20 tests will look significant by chance. Corrections such as Bonferroni or controlling the false discovery rate (Benjamini–Hochberg) address it.

Q37

What is p-hacking?

Trying many analyses, subsets or stopping points until something becomes significant, then reporting only that. Avoid it by pre-registering the hypothesis and metric, fixing sample size in advance and reporting all tests.

Q38

Statistical significance vs practical significance?

A result can be statistically significant but too small to matter — a 0.1% conversion lift with millions of users. Always report the effect size and confidence interval and judge whether the change is worth acting on.

Q39

What is an effect size?

A measure of how large a difference or relationship is, independent of sample size — for example the difference in means, Cohen's d or a percentage lift. It's what decision-makers actually care about.

Q40

How do you calculate sample size for an A/B test?

Decide the baseline rate, the minimum detectable effect, significance level (α, usually 0.05) and power (usually 80%), then use a power calculation. Smaller effects and noisier metrics need much larger samples.

Q41

Why shouldn't you stop an A/B test as soon as it looks significant?

Peeking repeatedly and stopping at the first significant result inflates the false-positive rate. Fix the duration or sample size in advance, or use sequential testing methods designed for continuous monitoring.

Q42

What is Simpson's paradox?

A trend that appears in several groups reverses when the groups are combined, because of a confounding variable such as group size. It's a reminder to segment data and think about confounders before drawing conclusions.

Q43

What is a confounding variable?

A variable that influences both the supposed cause and the effect, creating a misleading association — ice cream sales and drownings both rise with temperature. Randomisation or controlling for confounders addresses it.

Q44

What is the difference between parametric and non-parametric tests?

Parametric tests (t-test, ANOVA) assume a distribution such as normality. Non-parametric tests (Mann–Whitney U, Wilcoxon, Kruskal–Wallis) make fewer assumptions and work on ranks — useful for small or skewed samples.

Q45

What is bootstrapping?

A resampling method: repeatedly sample from your data with replacement and recompute the statistic, building an empirical distribution. It gives confidence intervals for almost any metric without strong distribution assumptions.

Q46

What is the standard error?

The standard deviation of a sample statistic, such as the mean, across repeated samples. For the mean it's SD / √n, so it shrinks as the sample grows — that's why larger samples give tighter estimates.

Q47

What is expected value?

The long-run average outcome of a random variable: the sum of each outcome times its probability. Businesses use it to compare options, such as the expected profit of a promotion.

Q48

What is maximum likelihood estimation?

A method that chooses the parameter values that make the observed data most probable under the model. It underpins logistic regression and many other statistical models.

Q49

Explain the difference between frequentist and Bayesian statistics.

Frequentists treat parameters as fixed and probability as long-run frequency, using p-values and confidence intervals. Bayesians treat parameters as uncertain, combine prior beliefs with data, and report posterior probabilities and credible intervals.

Q50

How would you explain a p-value to a non-technical manager?

"If the new design truly made no difference, there would be only a 3% chance of seeing a result this big by luck. That's unlikely, so we think the improvement is real — and here is how big it is likely to be."

04

Machine Learning interview questions

Concepts every ML interview covers, from algorithms and bias-variance to evaluation metrics, deep learning and deployment. 50 questions

Q1

What is the bias-variance trade-off?

Bias is error from overly simple assumptions (underfitting); variance is error from being too sensitive to the training data (overfitting). Making a model more complex lowers bias but raises variance. The goal is the complexity that minimises total error on unseen data.

Q2

How do you detect and prevent overfitting?

Detect it when training performance is much better than validation performance. Prevent it with more data, cross-validation, simpler models, regularisation (L1/L2), dropout in neural networks, early stopping, and pruning or limiting depth in tree models.

Q3

What is the difference between L1 and L2 regularisation?

Both add a penalty on weight size to the loss. L1 (Lasso) penalises absolute values and can push some weights to exactly zero, so it also performs feature selection. L2 (Ridge) penalises squared values, shrinking all weights smoothly, and handles correlated features well.

Q4

Precision vs recall — when do you prioritise each?

Precision = of the items predicted positive, how many were right. Recall = of the actual positives, how many we found. Prioritise recall when missing a positive is costly (fraud, disease screening); prioritise precision when false alarms are costly (spam filtering). F1 balances the two.

Q5

Why is accuracy misleading on imbalanced data?

If 99% of transactions are genuine, a model that predicts 'genuine' every time is 99% accurate but useless. Use precision, recall, F1, ROC-AUC or PR-AUC instead, and consider class weights, resampling or threshold tuning.

Q6

How does a random forest work?

It trains many decision trees, each on a bootstrap sample of the rows and a random subset of features at each split, then averages their predictions (regression) or takes a majority vote (classification). The randomness de-correlates the trees, which reduces variance compared to a single tree.

Q7

Bagging vs boosting?

Bagging trains models independently in parallel on resampled data and averages them, mainly reducing variance (e.g. random forest). Boosting trains models sequentially, each one focusing on the previous models' errors, mainly reducing bias (e.g. XGBoost, LightGBM).

Q8

What is cross-validation?

In k-fold cross-validation the data is split into k parts; the model trains on k−1 parts and is validated on the remaining one, rotating k times. Averaging the k scores gives a more reliable performance estimate than a single train/test split and helps with hyperparameter tuning.

Q9

Supervised vs unsupervised vs reinforcement learning?

Supervised learning learns from labelled examples to predict a target. Unsupervised learning finds structure in unlabelled data, such as clusters. Reinforcement learning trains an agent to take actions that maximise reward through trial and error.

Q10

Classification vs regression?

Classification predicts a category (churn or not, spam or not); regression predicts a continuous number (price, demand). Some algorithms, like decision trees and gradient boosting, can do both.

Q11

How does linear regression work?

It fits a line (or hyperplane) that predicts the target as a weighted sum of features plus an intercept, choosing weights that minimise the sum of squared errors. It's simple, fast and highly interpretable.

Q12

How does logistic regression work?

It computes a weighted sum of features and passes it through the sigmoid function to get a probability between 0 and 1, then applies a threshold (often 0.5) to classify. It's trained by minimising log loss and is a strong, interpretable baseline.

Q13

How does a decision tree decide where to split?

At each node it tries possible splits and picks the one that best separates the target — maximising information gain (entropy reduction) or Gini impurity reduction for classification, or variance reduction for regression.

Q14

Why do decision trees overfit, and how do you control it?

An unrestricted tree keeps splitting until it memorises the training data. Control it with max_depth, min_samples_leaf, min_samples_split, pruning, or by using ensembles such as random forests and gradient boosting.

Q15

How does gradient boosting work?

It builds trees one after another; each new tree is trained on the residual errors (gradients of the loss) of the current ensemble, and its predictions are added with a learning rate. XGBoost, LightGBM and CatBoost are popular, fast implementations.

Q16

How does k-nearest neighbours (KNN) work?

To predict a new point, KNN finds the k closest training points by a distance measure and takes a majority vote (classification) or average (regression). It needs scaled features and becomes slow on large datasets.

Q17

What is a support vector machine (SVM)?

An SVM finds the boundary that separates classes with the widest possible margin. The kernel trick lets it learn non-linear boundaries by implicitly mapping data to higher dimensions. It works well on medium-sized, high-dimensional data.

Q18

What is Naive Bayes and why is it 'naive'?

It applies Bayes' theorem to classify, assuming features are independent given the class — rarely true, hence 'naive'. It's fast and works surprisingly well for text classification such as spam detection.

Q19

How does k-means clustering work?

Choose k, place k centroids, assign each point to the nearest centroid, move each centroid to the mean of its points, and repeat until assignments stop changing. It assumes roughly spherical clusters and needs scaled features.

Q20

How do you choose k in k-means?

Use the elbow method (plot inertia against k and look for the bend), silhouette scores, and — most importantly — whether the clusters make business sense and are actionable.

Q21

What is PCA?

Principal Component Analysis reduces dimensions by projecting data onto new, uncorrelated axes (principal components) that capture the most variance. It's used for visualisation, noise reduction and speeding up models; features should be scaled first.

Q22

What is the curse of dimensionality?

As features increase, data becomes sparse and distances between points become less meaningful, so models need far more data and distance-based methods like KNN degrade. Feature selection and dimensionality reduction help.

Q23

What is feature engineering?

Creating better model inputs from raw data — ratios, date parts, aggregates over time windows, text features, interaction terms. Good features often improve a model more than switching algorithms.

Q24

How do you encode categorical variables?

One-hot encoding for nominal categories with few values; ordinal encoding when categories have an order; target encoding or embeddings for high-cardinality columns, done carefully inside cross-validation to avoid leakage.

Q25

Why scale features, and standardisation vs normalisation?

Distance- and gradient-based models (KNN, SVM, neural networks, regularised regression) are sensitive to feature scale. Standardisation rescales to mean 0 and SD 1; min-max normalisation rescales to a 0–1 range. Tree models generally don't need scaling.

Q26

What is data leakage?

When information that wouldn't be available at prediction time sneaks into training — for example a 'refund issued' column when predicting fraud, or scaling the full dataset before splitting. It produces great validation scores and poor real-world results.

Q27

Why do you need train, validation and test sets?

Train fits the model, validation is used to tune hyperparameters and choose models, and the untouched test set gives a final, unbiased estimate. Reusing the test set for tuning makes its score optimistic.

Q28

Hyperparameters vs parameters?

Parameters are learned from data (regression weights, tree splits). Hyperparameters are set before training (learning rate, max_depth, number of trees, k) and are tuned with validation data.

Q29

Grid search vs random search?

Grid search tries every combination of chosen values — thorough but expensive. Random search samples combinations and often finds good settings faster when only a few hyperparameters matter. Bayesian optimisation is a smarter third option.

Q30

What is a confusion matrix?

A table of true positives, false positives, true negatives and false negatives for a classifier. Precision, recall, specificity and accuracy are all calculated from it, and it shows exactly which mistakes the model makes.

Q31

What is ROC-AUC?

The ROC curve plots true positive rate against false positive rate across all thresholds; AUC is the area under it — the probability the model ranks a random positive above a random negative. 0.5 is random, 1.0 is perfect.

Q32

When is PR-AUC better than ROC-AUC?

With heavy class imbalance, ROC-AUC can look good even when the model produces many false positives. The precision-recall curve focuses on the positive class, so PR-AUC better reflects performance for rare events like fraud.

Q33

Which metrics do you use for regression?

MAE (average absolute error, easy to explain), RMSE (penalises large errors more), MAPE (percentage error, problematic near zero) and R². Choose the one that matches the business cost of errors.

Q34

How do you choose a classification threshold?

Don't default to 0.5. Plot precision and recall against thresholds and pick the point that matches business costs — for example the threshold that keeps false alarms manageable while catching most fraud.

Q35

How do you handle missing data before modelling?

Understand why it's missing, then drop, impute (mean/median/mode, model-based) or add a 'was missing' indicator. Fit imputers on training data only. Some models, like gradient boosting libraries, handle missing values natively.

Q36

What is ensemble learning and stacking?

Ensembles combine several models to get better, more stable predictions — bagging, boosting and stacking. Stacking trains a meta-model on the predictions of several base models.

Q37

What is a neural network?

Layers of connected units (neurons) that each compute a weighted sum of inputs and apply a non-linear activation. Stacking layers lets the network learn complex patterns; weights are learned with backpropagation and gradient descent.

Q38

What is backpropagation?

The algorithm that computes how much each weight contributed to the error by applying the chain rule backwards from the output layer. These gradients are then used by an optimiser to update the weights.

Q39

What are activation functions and why are they needed?

Non-linear functions applied to each neuron's output — ReLU, sigmoid, tanh, softmax. Without them, a deep network would collapse into a single linear model and couldn't learn complex patterns.

Q40

What is gradient descent, and what does the learning rate do?

Gradient descent updates parameters in the direction that reduces the loss. The learning rate sets the step size: too high and training diverges or oscillates, too low and it's slow or gets stuck. Adam and SGD with momentum are common optimisers.

Q41

What are vanishing and exploding gradients?

In deep networks, gradients can shrink towards zero (so early layers stop learning) or grow huge (unstable training). Fixes include ReLU activations, careful initialisation, batch normalisation, residual connections and gradient clipping.

Q42

What is dropout?

A regularisation technique that randomly switches off a fraction of neurons during training, forcing the network not to rely on any single path. It's turned off at inference time.

Q43

What is a CNN used for?

Convolutional neural networks use learnable filters that slide over images to detect edges, textures and shapes, building up to objects. They're used for image classification, object detection and medical imaging.

Q44

RNNs, LSTMs and transformers — how do they differ?

RNNs process sequences step by step but struggle with long-range dependencies; LSTMs add gates to remember information longer. Transformers use self-attention to look at all positions at once, train in parallel and now dominate NLP.

Q45

What is transfer learning?

Starting from a model pre-trained on a large dataset and fine-tuning it for your task — for example a pre-trained image model adapted to classify product photos. It needs far less data and compute than training from scratch.

Q46

What is an imbalanced dataset and how do you fix it?

When one class is much rarer than another. Use suitable metrics, class weights, oversampling (e.g. SMOTE) or undersampling inside cross-validation, collect more minority examples and tune the decision threshold.

Q47

How do you explain a model's predictions?

Use global importance (permutation importance, feature importances) and local explanations such as SHAP values or LIME for individual predictions, plus partial dependence plots. Simple models like logistic regression are explainable by design.

Q48

How do you deploy a machine learning model?

Save the trained model and preprocessing pipeline, wrap them in an API (e.g. FastAPI) or batch job, containerise with Docker, version the model and data, and monitor latency, errors and prediction quality after release.

Q49

What is model drift and how do you monitor it?

Data drift is when input distributions change; concept drift is when the relationship between inputs and target changes. Monitor input statistics and live performance, set alerts, and retrain on recent data when quality drops.

Q50

Walk me through how you would build a churn prediction model.

Define churn and the prediction window with the business, assemble historical features (usage, tenure, complaints, payments) without leakage, split by time, start with a logistic regression baseline then try gradient boosting, evaluate with PR-AUC and recall at a useful threshold, explain drivers with SHAP, and plan how the retention team will act on the scores.

05

Data Analytics, Excel & Power BI interview questions

Practical questions for data analyst and BI roles — cleaning, KPIs, Excel formulas, Power Query, DAX, dashboards and stakeholder skills. 50 questions

Q1

How do you handle missing values in a dataset?

First find out why they are missing. Then drop rows or columns if the missing share is small or the column is not useful; impute with the mean or median (numeric) or mode (categorical); use a model-based or forward-fill method for time series; or add a 'missing' flag if missingness itself carries information.

Q2

VLOOKUP vs XLOOKUP vs INDEX-MATCH?

VLOOKUP searches only the first column of a range and returns a value to its right, and breaks if columns are inserted. INDEX-MATCH can look left and is more robust. XLOOKUP (newer Excel) does both, defaults to exact match, and can return a custom value when nothing is found.

Q3

What is DAX, and what does CALCULATE do in Power BI?

DAX is Power BI's formula language for measures and calculated columns. CALCULATE evaluates an expression under a modified filter context — for example CALCULATE(SUM(Sales[Amount]), Sales[Region] = "South") — and is the foundation of most time-intelligence and comparison measures.

Q4

Calculated column vs measure in Power BI?

A calculated column is computed row by row when data refreshes and stored in the model (it uses memory). A measure is computed at query time based on the current filters in a visual. Use measures for aggregations such as totals, ratios and year-on-year growth.

Q5

What is a star schema?

A data-model design with a central fact table (events such as sales, with numeric measures and foreign keys) surrounded by dimension tables (date, product, customer, store). It keeps models simple and fast, and is the recommended structure for Power BI.

Q6

How do you present insights to non-technical stakeholders?

Lead with the business question and the answer, then show the one or two charts that support it. Use plain language, quantify the impact, call out limitations honestly, and end with a clear recommendation or next step.

Q7

What does a data analyst do day to day?

Gathers requirements from business teams, pulls data with SQL, cleans and analyses it in Excel or Python, builds reports and dashboards, tracks KPIs, investigates changes ('why did sales drop?') and presents findings with recommendations.

Q8

Walk me through your data analysis process.

Clarify the question and success metric, identify and collect data, clean and validate it, explore with summaries and charts, analyse (segmenting, comparing, testing), then communicate findings and recommendations — and follow up on what was done with them.

Q9

What is data cleaning, and what issues do you look for?

Fixing data so it's accurate and usable: missing values, duplicates, inconsistent formats (dates, phone numbers, city spellings), wrong data types, outliers, invalid values and mismatched keys between tables.

Q10

How do you validate that your numbers are correct?

Reconcile totals with a trusted source, check row counts before and after joins, spot-check individual records, look for duplicates introduced by joins, compare with previous periods and ask a domain expert whether the result makes sense.

Q11

What is exploratory data analysis (EDA)?

An initial investigation of a dataset — shape, data types, summary statistics, distributions, missing values, outliers and relationships between variables — using tables and charts before formal analysis or modelling.

Q12

What is the difference between descriptive, diagnostic, predictive and prescriptive analytics?

Descriptive: what happened. Diagnostic: why it happened. Predictive: what is likely to happen. Prescriptive: what we should do about it. Most analyst work is descriptive and diagnostic.

Q13

What are KPIs, and how do you choose good ones?

Key performance indicators measure progress towards a business goal — conversion rate, revenue per customer, churn rate. Good KPIs are tied to a goal, clearly defined, measurable from reliable data, and owned by someone who can act on them.

Q14

What is a pivot table?

An Excel (or Google Sheets) tool that summarises data by dragging fields into rows, columns, values and filters — for example total sales by region and month — without writing formulas. Pivot charts visualise the result.

Q15

What is conditional formatting used for?

Automatically highlighting cells based on rules — values above target in green, duplicates in red, colour scales or data bars — so patterns and exceptions stand out in a sheet.

Q16

SUMIF vs SUMIFS vs COUNTIFS?

SUMIF adds values that meet one condition; SUMIFS adds values that meet several conditions (e.g. region = South and month = March); COUNTIFS counts rows meeting several conditions. They're the formula-based alternative to pivot tables.

Q17

How do you remove duplicates in Excel?

Use Data → Remove Duplicates on the chosen columns, or the UNIQUE() function to return distinct values dynamically. Check first which columns define a duplicate, and keep a copy of the original data.

Q18

What is data validation in Excel?

Rules that restrict what users can enter in cells — drop-down lists, number or date ranges, text length — with optional input messages and error alerts. It keeps manually entered data clean.

Q19

What are absolute and relative references in Excel?

A relative reference (A1) shifts when a formula is copied; an absolute reference ($A$1) stays fixed. Mixed references ($A1 or A$1) lock only the column or row — essential for copying formulas across tables.

Q20

What is Power Query?

The data-preparation engine in Excel and Power BI. It connects to sources, then cleans and reshapes data through recorded, repeatable steps — removing columns, splitting, merging, unpivoting and changing types — so refreshes apply the same transformations automatically.

Q21

What are the main components of Power BI?

Power BI Desktop for building reports (Power Query for data prep, a data model with DAX, and report visuals), the Power BI Service for publishing, sharing, scheduling refresh and dashboards, and mobile apps for viewing.

Q22

Report vs dashboard in Power BI?

A report is a multi-page, interactive analysis built from one dataset in Power BI Desktop. A dashboard (in the Power BI Service) is a single-page canvas of pinned tiles that can come from several reports, used for at-a-glance monitoring.

Q23

What is filter context vs row context in DAX?

Filter context is the set of filters applied to a calculation by slicers, visuals and CALCULATE. Row context is the current row when iterating, as in calculated columns or iterator functions like SUMX. Understanding both explains most DAX results.

Q24

SUM vs SUMX in DAX?

SUM adds up a single column. SUMX iterates over a table row by row, evaluates an expression for each row (e.g. Quantity × Price) and then sums the results.

Q25

How do you calculate year-over-year growth in Power BI?

Create a measure for the current value, then the prior-year value with CALCULATE([Sales], SAMEPERIODLASTYEAR('Date'[Date])), and divide: DIVIDE([Sales] - [Sales LY], [Sales LY]). It needs a proper, marked date table.

Q26

Why do you need a date table in Power BI?

Time-intelligence functions need a continuous calendar table with one row per date, marked as the date table and related to the fact table. It also gives consistent year, quarter, month and week columns for slicing.

Q27

What are relationships and cardinality in Power BI?

Relationships link tables on key columns so filters flow between them. Cardinality describes the link — one-to-many is the norm (one product, many sales), while many-to-many should be used carefully. Filter direction controls which way filters travel.

Q28

What is row-level security (RLS)?

A Power BI feature that restricts the data each user sees using DAX filter rules on roles — for example regional managers see only their region's sales — while sharing one report.

Q29

Import vs DirectQuery in Power BI?

Import loads data into Power BI's compressed in-memory engine — fast, but refreshed on a schedule. DirectQuery leaves data in the source and queries it live — always current, but slower and with some modelling limits.

Q30

How do you improve a slow Power BI report?

Use a star schema, remove unused columns and rows, prefer measures over calculated columns, reduce high-cardinality columns, limit visuals per page, avoid complex bi-directional relationships, and check Performance Analyzer to find slow visuals and DAX.

Q31

What makes a good dashboard?

A clear purpose and audience, the most important KPIs at the top, consistent layout and colours, the right chart for each question, minimal clutter, useful filters, clear labels and definitions, and data people trust.

Q32

How do you choose the right chart?

Line charts for trends over time, bar charts for comparing categories, stacked bars for parts of a whole across groups, scatter plots for relationships, histograms for distributions, and tables when exact values matter. Avoid 3D and crowded pie charts.

Q33

What is cohort analysis?

Grouping users by a shared starting point — such as signup month — and tracking their behaviour over time, like retention by month since signup. It shows whether newer customers behave better or worse than older ones.

Q34

What is funnel analysis?

Measuring how many users move through each step of a process — visit → sign up → add to cart → pay — and where they drop off. It points to the steps worth fixing first.

Q35

What is RFM analysis?

Customer segmentation by Recency (how recently they bought), Frequency (how often) and Monetary value (how much). It identifies best customers, at-risk customers and those to win back.

Q36

How do you analyse a sudden drop in sales?

Confirm the data is correct, then break the drop down by time, region, channel, product and customer segment to locate it; check for tracking changes, outages, pricing or stock issues, competitor actions and seasonality; and quantify each likely cause.

Q37

What is A/B testing from an analyst's perspective?

Comparing two versions — say two landing pages — by randomly splitting users and measuring a pre-defined metric. The analyst checks the sample size, runs the significance test, reviews guardrail metrics and explains whether the change is worth rolling out.

Q38

What is the difference between a data analyst and a business analyst?

Data analysts focus on extracting, analysing and visualising data to answer questions. Business analysts focus on understanding business processes and requirements and translating them into solutions; the roles often overlap.

Q39

What is ETL?

Extract data from sources, Transform it (clean, join, aggregate) and Load it into a destination such as a data warehouse. Analysts often do lightweight ETL with SQL, Power Query or Python.

Q40

What is a data warehouse?

A central database designed for analysis that stores cleaned, integrated historical data from many systems, usually modelled as star schemas. Examples include BigQuery, Snowflake, Redshift and Azure Synapse.

Q41

How do you use Python as a data analyst?

Pandas to load, clean, merge and aggregate data; Matplotlib or Seaborn for charts; Jupyter notebooks for exploration; and scripts to automate repetitive reports and pull data from APIs or databases.

Q42

How do you merge two datasets in Pandas?

Use pd.merge(left, right, on='customer_id', how='left'), choosing inner, left, right or outer like SQL joins. Check row counts afterwards to make sure the join didn't create duplicates.

Q43

What does groupby do in Pandas?

It splits data into groups by one or more columns, applies an aggregation or function to each group and combines the results: df.groupby('city')['revenue'].agg(['sum', 'mean']).

Q44

How do you handle outliers in an analysis?

Identify them with box plots, z-scores or the IQR rule, investigate whether they're errors or genuine extremes, then correct errors, and for genuine values consider medians, capping or analysing them separately — and say what you did.

Q45

What is a data dictionary?

Documentation listing each table and column with its meaning, data type, allowed values, source and owner. It helps everyone interpret data consistently and speeds up onboarding.

Q46

How do you prioritise multiple data requests?

Clarify the business impact and deadline of each, agree priorities with stakeholders, deliver quick wins early, reuse existing reports where possible, and communicate timelines openly.

Q47

Tell me about a time your analysis changed a decision.

Use the STAR method — Situation, Task, Action, Result — with a specific example: the question, the data you used, what you found and the measurable effect of the decision it led to.

Q48

How do you ensure data privacy in your work?

Access only the data needed, mask or aggregate personal information in reports, follow company policy and applicable law on personal data, store files securely, and avoid sharing raw data by email or personal devices.

Q49

What is the difference between a metric and a dimension?

A metric is a number you measure (revenue, orders, sessions). A dimension is an attribute you slice metrics by (date, city, channel, product category).

Q50

If a stakeholder disagrees with your findings, what do you do?

Listen to their reasoning, re-check the data and assumptions together, show the method transparently, test their alternative explanation with data, and agree on what additional evidence would settle it.

06

Generative AI & LLMs interview questions

Questions for GenAI, LLM and AI engineer interviews — transformers, prompting, embeddings, RAG, fine-tuning, safety and cost. 50 questions

Q1

What is a large language model (LLM)?

An LLM is a neural network — usually a transformer — trained on very large amounts of text to predict the next token. That simple objective, at scale, lets it summarise, answer questions, write code and follow instructions. Examples include the GPT, Claude, Gemini and Llama model families.

Q2

What is a token, and why does the context window matter?

A token is a chunk of text — often part of a word — that the model reads and writes. The context window is the maximum number of tokens the model can consider at once (prompt plus response). It limits how much document text or chat history you can include, and token count also drives cost and latency.

Q3

What is Retrieval-Augmented Generation (RAG)?

RAG fetches relevant passages from your own data — typically by embedding the question and searching a vector database — and adds them to the prompt so the LLM answers from those sources. It reduces hallucinations, keeps answers current without retraining, and lets you cite sources.

Q4

What are embeddings?

Embeddings are numeric vectors that represent the meaning of text (or images) so that similar meanings sit close together in vector space. They power semantic search, clustering, recommendations and the retrieval step in RAG; similarity is usually measured with cosine similarity.

Q5

Fine-tuning vs prompt engineering vs RAG — how do you choose?

Start with prompt engineering: it is the cheapest and fastest. Add RAG when the model needs your private or frequently changing knowledge. Consider fine-tuning when you need a consistent style or format, or a specialised task the base model does poorly, and you have good training examples.

Q6

What is hallucination, and how do you reduce it?

Hallucination is when a model states something fluent but false. Reduce it by grounding answers with RAG, asking the model to cite sources or say 'I don't know', lowering temperature for factual tasks, validating outputs against rules or tools, and evaluating with test sets.

Q7

What does the temperature parameter control?

Temperature controls randomness in token sampling. Low values (around 0–0.3) make outputs focused and repeatable — good for extraction and factual answers. Higher values make outputs more varied — useful for brainstorming or creative writing.

Q8

What is generative AI?

AI that creates new content — text, code, images, audio, video — rather than only classifying or predicting. It's powered mainly by large language models for text and code, and diffusion or transformer models for images and media.

Q9

What is the transformer architecture?

A neural network architecture based on self-attention, introduced in 2017's 'Attention Is All You Need'. It processes all tokens in parallel and learns which tokens to focus on for each token, which made training very large language models practical.

Q10

What is self-attention?

For each token, self-attention computes how relevant every other token is (using query, key and value vectors) and builds a context-aware representation as a weighted mix. It lets the model connect words that are far apart in a sentence.

Q11

What is multi-head attention?

Running several attention operations in parallel, each with its own learned projections, then combining them. Different heads can capture different relationships — syntax, references, topic — at the same time.

Q12

Why do transformers need positional encoding?

Attention itself doesn't know token order. Positional encodings (fixed sinusoidal, learned, or rotary embeddings such as RoPE) add order information so the model can tell 'dog bites man' from 'man bites dog'.

Q13

Encoder-only vs decoder-only vs encoder-decoder models?

Encoder-only models (BERT) read the whole input and are great for classification and embeddings. Decoder-only models (GPT-style) generate text left to right and power most chat LLMs. Encoder-decoder models (T5) map an input sequence to an output sequence, as in translation.

Q14

What is pre-training vs fine-tuning?

Pre-training teaches a model general language patterns from huge unlabelled text by predicting tokens. Fine-tuning then adapts it to specific behaviour or tasks with smaller, curated datasets — instructions, conversations or domain examples.

Q15

What is instruction tuning?

Fine-tuning a pre-trained model on many examples of instructions paired with good responses, so it follows user requests instead of simply continuing text.

Q16

What is RLHF?

Reinforcement Learning from Human Feedback: humans rank model responses, a reward model learns those preferences, and the LLM is optimised to produce responses the reward model scores highly. It improves helpfulness and safety. Alternatives such as DPO learn directly from preference pairs.

Q17

What is prompt engineering?

Designing prompts that reliably produce the output you want: clear instructions, relevant context, examples, a defined output format and constraints. Good practice is to test prompts against a set of cases, not just one example.

Q18

Zero-shot, one-shot and few-shot prompting?

Zero-shot gives only an instruction; one-shot adds a single example; few-shot adds several examples of input and desired output. Examples help the model match format and style, especially for unusual tasks.

Q19

What is chain-of-thought prompting?

Asking the model to work through a problem step by step before giving a final answer. It can improve performance on reasoning, maths and multi-step tasks; many newer models also perform this kind of reasoning internally.

Q20

What is a system prompt?

Instructions set by the application, not the end user, that define the model's role, rules, tone and output format for the whole conversation — for example 'You are a support assistant; answer only from the provided documents.'

Q21

What are top-p and top-k sampling?

Ways to limit which tokens the model can choose. Top-k samples from the k most likely tokens; top-p (nucleus sampling) samples from the smallest set whose probabilities add up to p. Both trade diversity against coherence, alongside temperature.

Q22

How do you get structured output (like JSON) from an LLM?

Describe the schema precisely, show an example, and use the API's structured-output or JSON mode or tool calling where available. Always validate the result with a schema validator and retry or repair on failure.

Q23

What is a vector database?

A database optimised to store embeddings and run fast similarity search, usually with approximate nearest-neighbour indexes. Examples include pgvector (PostgreSQL), Pinecone, Weaviate, Qdrant, Milvus and Chroma.

Q24

Cosine similarity vs Euclidean distance?

Cosine similarity measures the angle between vectors, focusing on direction (meaning) rather than length. Euclidean distance measures straight-line distance. For normalised embeddings they give equivalent rankings; cosine is the usual choice for text.

Q25

What is chunking in RAG, and how do you choose chunk size?

Splitting documents into smaller passages before embedding. Chunks should be small enough to be specific but large enough to keep context — often a few hundred tokens with some overlap, ideally split on headings or paragraphs. Test sizes against real questions.

Q26

What is hybrid search?

Combining keyword search (such as BM25) with vector search. Keywords catch exact terms like product codes and names; vectors catch meaning. Merging both usually retrieves better context for RAG than either alone.

Q27

What is re-ranking in RAG?

After retrieving a broader set of candidates, a re-ranker model (often a cross-encoder) scores each passage against the question more precisely and keeps the best few. It improves relevance at modest extra cost.

Q28

How do you evaluate a RAG system?

Evaluate retrieval (did we fetch the right passages? recall, precision at k) and generation (is the answer faithful to the sources, relevant and complete?). Use a test set of real questions with expected answers, human review, and LLM-as-judge with care.

Q29

What causes a RAG system to give wrong answers?

Common causes: the right document was never indexed, poor chunking, weak retrieval or no re-ranking, too much irrelevant context, outdated data, or the prompt not forcing the model to stick to the sources. Debug retrieval first.

Q30

What is LoRA?

Low-Rank Adaptation is a parameter-efficient fine-tuning method that freezes the original weights and trains small low-rank matrices added to certain layers. It cuts memory and compute dramatically; QLoRA combines it with a quantised base model.

Q31

What is quantisation?

Storing model weights with fewer bits — for example 8-bit or 4-bit instead of 16-bit — to reduce memory and speed up inference, usually with a small loss in quality. It's how large open models run on modest hardware.

Q32

What is knowledge distillation?

Training a smaller 'student' model to imitate a larger 'teacher' model's outputs, producing a faster, cheaper model that keeps much of the teacher's ability.

Q33

What is prompt injection, and how do you defend against it?

Malicious instructions hidden in user input or retrieved content that try to override your system prompt — for example a web page saying 'ignore previous instructions'. Defend by separating instructions from data, limiting tool permissions, validating outputs, filtering inputs and requiring human approval for risky actions.

Q34

What is jailbreaking?

Crafting prompts that trick a model into ignoring its safety rules. Providers mitigate it with safety training and filters; applications add their own moderation, restricted capabilities and monitoring.

Q35

How do you reduce LLM cost and latency?

Use the smallest model that meets quality, shorten prompts, cache repeated prompts and results, retrieve fewer but better chunks, stream responses, batch requests, and route only hard queries to larger models.

Q36

What is streaming in LLM APIs?

Receiving the response token by token as it's generated instead of waiting for the whole answer. It makes chat interfaces feel much faster, even though total generation time is similar.

Q37

What is multimodal AI?

Models that understand or generate more than one type of data — text, images, audio, video. Examples: describing a chart image, answering questions about a PDF with diagrams, or generating images from text.

Q38

How do image generation (diffusion) models work, briefly?

Diffusion models learn to reverse a gradual noising process: starting from random noise, they denoise step by step, guided by a text prompt's embedding, until a coherent image emerges.

Q39

Open-source vs closed (API) LLMs — trade-offs?

Closed API models are usually the most capable and easy to use, but you depend on the provider and send data to them. Open-weight models can be self-hosted for privacy, control and customisation, but need infrastructure and expertise.

Q40

What is a context-length limitation, and how do you work around it?

Models can only read a fixed number of tokens at once. Work around it with retrieval (send only relevant chunks), summarising long histories, map-reduce summarisation over long documents, and choosing long-context models when needed.

Q41

What is LLM evaluation, and why is it hard?

Measuring output quality — correctness, faithfulness, helpfulness, safety, format. It's hard because answers are open-ended. Use task-specific test sets, automatic checks where possible, human review and carefully calibrated LLM-as-judge methods.

Q42

What is LLM-as-a-judge?

Using a strong LLM with a rubric to grade another model's outputs at scale. It's useful but can be biased (towards longer answers or its own style), so validate it against human ratings.

Q43

What are guardrails in generative AI apps?

Checks around the model: input filtering, topic restrictions, output validation (schemas, banned content, PII detection), grounding checks, rate limits and human review for high-risk outputs.

Q44

What are common generative AI use cases in companies?

Customer support assistants, internal knowledge search, document summarisation, data extraction from forms and emails, code assistance, content drafting, meeting notes and sales email personalisation — usually with a human reviewing important outputs.

Q45

What is LangChain or LlamaIndex used for?

Frameworks that provide building blocks for LLM apps — model wrappers, prompt templates, document loaders, chunking, vector store integrations, retrieval pipelines and agents. Many teams also build directly on provider SDKs for more control.

Q46

How do you handle personal data in LLM applications?

Minimise what you send, mask or remove PII where possible, check the provider's data retention and training policies, restrict access to logs, comply with applicable data-protection law, and keep sensitive workloads on approved infrastructure.

Q47

What is model 'grounding'?

Making a model's answer depend on specific, verifiable sources — retrieved documents, database results or tool outputs — rather than its general training data, and ideally citing those sources.

Q48

What is semantic caching?

Caching LLM responses keyed by the meaning of the query (via embeddings) rather than the exact text, so similar questions reuse a previous answer. It cuts cost and latency for repetitive queries, with a similarity threshold to avoid wrong matches.

Q49

How would you build a document Q&A assistant for a company?

Collect and clean documents, chunk them with metadata, embed and index in a vector store, retrieve with hybrid search and re-ranking, prompt the LLM to answer only from the retrieved passages with citations, add access control per user, and evaluate with real employee questions before launch.

Q50

How do you explain generative AI's limitations to a business stakeholder?

It produces fluent text but can be confidently wrong, doesn't know your private data unless you connect it, can be inconsistent, and costs money per use. It works best for drafting, summarising and searching, with humans reviewing important decisions.

07

Agentic AI interview questions

Questions for teams building AI agents — tool calling, planning, memory, multi-agent systems, MCP, evaluation and guardrails. 50 questions

Q1

What is an AI agent?

An AI agent is an LLM-driven system that pursues a goal over multiple steps: it plans, calls tools (search, code, APIs, databases), observes the results and decides what to do next, rather than producing a single response to a single prompt.

Q2

What is tool (function) calling?

Tool calling lets a model return a structured request — a function name plus JSON arguments — instead of plain text. Your code runs the function (for example get_weather or query_crm) and passes the result back, so the model can act on real data and systems.

Q3

Explain the ReAct pattern.

ReAct (Reason + Act) interleaves reasoning and actions: the model thinks about the next step, calls a tool, reads the observation, and repeats until it can answer. It makes agent behaviour easier to follow and debug than a single opaque response.

Q4

What is the Model Context Protocol (MCP)?

MCP is an open protocol for connecting AI applications to external tools and data sources through a standard interface. A tool or data source is exposed once as an MCP server and can then be used by any MCP-compatible client, instead of writing a custom integration for every app.

Q5

How do you make an AI agent reliable in production?

Give it narrow, well-described tools; validate tool inputs and outputs; set step and cost limits; keep a human in the loop for risky actions such as payments or deletions; log every step for tracing; and build an evaluation set of real tasks to test changes before you deploy them.

Q6

How is agentic AI different from a chatbot?

A chatbot mainly responds to messages. An agent takes actions towards a goal: it breaks the task down, calls tools, checks results and continues until done — for example researching a topic, updating a CRM and drafting an email in one run.

Q7

What are the core components of an agent?

A model that reasons and decides, tools it can call, instructions defining its goal and rules, memory or state to track progress, and an orchestration loop that runs steps, handles errors and decides when to stop.

Q8

What is the agent loop?

The repeated cycle of: decide the next action → call a tool or respond → observe the result → update state → decide again, until the goal is met, a step limit is reached or a human needs to step in.

Q9

How do you design good tools for an agent?

Make each tool do one clear job, give it a descriptive name and docstring, define strict input schemas, return concise structured results with helpful error messages, and avoid overlapping tools that confuse the model.

Q10

Why do tool descriptions matter so much?

The model chooses tools and fills arguments based only on their names, descriptions and schemas. Vague descriptions lead to wrong tool choices and bad arguments; clear ones with examples and constraints greatly improve reliability.

Q11

What is planning in agents?

Breaking a goal into ordered sub-tasks before or during execution. Approaches include plan-then-execute (make a full plan, then run it) and iterative planning (decide one step at a time and re-plan as results arrive).

Q12

Plan-and-execute vs ReAct?

Plan-and-execute writes a full plan first and then carries out the steps — efficient and easy to review for predictable tasks. ReAct decides step by step from observations — more adaptive for uncertain tasks but can wander without limits.

Q13

What types of memory can agents have?

Short-term memory is the current conversation and scratchpad in the context window. Long-term memory persists across sessions — facts, preferences, past results — usually stored in a database or vector store and retrieved when relevant.

Q14

How do you stop an agent's context from growing too large?

Summarise earlier steps, keep only relevant tool outputs, store large results externally and pass references, trim tool responses to the fields needed, and split work across sub-agents with their own contexts.

Q15

What is a multi-agent system?

Several specialised agents working together — for example a researcher, a writer and a reviewer — coordinated by a supervisor or by passing messages. It helps with complex tasks but adds coordination cost and new failure modes.

Q16

Supervisor (orchestrator–worker) pattern?

A supervisor agent receives the task, breaks it down, delegates sub-tasks to worker agents with specific tools, collects their results and assembles the final answer. It keeps each worker focused and easier to test.

Q17

When should you NOT use multiple agents?

When a single agent with good tools — or a simple deterministic workflow — can do the job. Multi-agent setups cost more tokens, are harder to debug and can amplify errors, so add them only when specialisation clearly helps.

Q18

Agents vs workflows — what's the difference?

In a workflow, the developer defines the steps and the LLM fills in parts (classify, extract, draft) along fixed paths. In an agent, the model decides the steps dynamically. Workflows are more predictable; agents are more flexible. Many production systems mix both.

Q19

What is human-in-the-loop?

Pausing the agent for human review or approval at key points — before sending emails, making payments, deleting data or when confidence is low. It balances automation with safety and accountability.

Q20

How do you evaluate an agent?

Build a test set of realistic tasks and measure task success rate, correctness of the final output, number of steps, cost and latency, tool-call errors and safety violations. Review full trajectories, not just final answers.

Q21

What is trajectory evaluation?

Assessing the whole sequence of an agent's reasoning and tool calls — did it choose sensible tools, in a sensible order, without unnecessary or risky steps — rather than only checking whether the final answer was right.

Q22

What are common agent failure modes?

Calling the wrong tool, invalid arguments, infinite loops, giving up too early, hallucinating tool results, losing track of the goal in long contexts, following injected instructions from web pages or documents, and running up costs.

Q23

How do you prevent infinite loops?

Set a maximum number of steps and a cost budget, detect repeated identical tool calls, require progress checks, and fall back to asking a human or returning a partial result when limits are reached.

Q24

What guardrails do agents need?

Least-privilege tool permissions, allow-lists for actions and domains, input and output validation, approval for irreversible actions, spending limits, rate limits, sandboxed code execution and complete logging for audit.

Q25

How does prompt injection threaten agents specifically?

Agents read untrusted content — web pages, emails, documents — that may contain instructions like 'send the data to this address'. Because agents can act, injection can cause real damage. Treat tool outputs as data, limit permissions and require approval for sensitive actions.

Q26

What is the principle of least privilege for agents?

Give an agent only the tools and access it needs for its task — read-only where possible, scoped to specific records or folders — so mistakes or attacks have limited impact.

Q27

How should an agent handle tool errors?

Tools should return clear, structured error messages. The agent can then retry with corrected arguments, try an alternative tool, or report the problem. Orchestration code should add retries with backoff for transient failures.

Q28

What is observability for agents?

Tracing every model call, tool call, input, output, latency and cost in a run so you can debug failures, find slow or expensive steps and monitor quality in production.

Q29

How do you control the cost of agents?

Use smaller models for simple steps, cap steps and tokens, cache tool results, keep context lean, avoid unnecessary multi-agent chatter, and monitor cost per task with alerts.

Q30

What are popular agent frameworks?

Examples include LangGraph, CrewAI, AutoGen, the OpenAI Agents SDK, the Claude Agent SDK and LlamaIndex agents. Many teams also write a simple loop directly with a provider's tool-calling API for full control.

Q31

What is LangGraph?

A library for building agents and workflows as graphs of nodes (steps) and edges (transitions) with shared state. It supports loops, branching, persistence and human-in-the-loop checkpoints.

Q32

What is an agent's state?

The information carried between steps — the goal, messages, intermediate results, which steps are done and any variables — that lets the agent resume, branch or hand off work reliably.

Q33

How do agents use RAG?

Retrieval becomes a tool: the agent decides when to search a knowledge base, can reformulate queries, search several sources and combine results — often called agentic RAG — instead of retrieving once before answering.

Q34

What is a coding agent?

An agent that reads a codebase, plans changes, edits files, runs tests or commands in a sandbox, inspects the results and iterates until the task passes. It needs strong sandboxing and review before changes are merged.

Q35

What is a computer-use or browser agent?

An agent that operates a browser or desktop by reading the screen and issuing clicks and keystrokes. It can automate tasks without APIs but is slower and needs careful safety controls.

Q36

How do you decide whether a task suits an agent?

Good candidates have a clear goal, need several steps or tools, have verifiable outcomes and tolerate occasional mistakes or allow review. Highly regulated, irreversible or simple single-step tasks are often better as fixed workflows.

Q37

What is reflection or self-critique in agents?

Having the agent (or a separate reviewer agent) critique its draft or plan against criteria and revise it. It can improve quality but adds cost and can't replace external verification such as tests.

Q38

How do you test changes to an agent safely?

Run the new version against a regression suite of recorded tasks, compare success rate, cost and safety metrics with the old version, review failures, then roll out gradually with monitoring.

Q39

What is an MCP server?

A program that exposes tools, resources (data) and prompts through the Model Context Protocol. Clients such as AI assistants connect to it and can then list and call its tools in a standard way.

Q40

How would you build an agent that books meetings?

Give it tools to read calendars, check availability, propose slots and send invites; define rules (working hours, time zones, meeting length); require confirmation before sending invites; handle conflicts and errors; and log every action.

Q41

How would you build a research agent?

Tools for web search, reading pages and taking notes; a plan step that breaks the question into sub-questions; a loop that searches, reads and records sources; a synthesis step with citations; and limits on steps and domains.

Q42

How do agents hand off work to humans?

By pausing with a clear summary of what was done, what's needed and why — then waiting for approval or input through a queue, ticket or chat message — and resuming from saved state afterwards.

Q43

What is agent autonomy level?

How much the agent can do without human approval — from suggesting actions only, to acting with approval, to fully autonomous within limits. Start low and increase autonomy as evaluation shows the agent is reliable.

Q44

Why do structured outputs matter for agents?

Agents pass data between steps and tools. Validated, schema-based outputs prevent parsing failures and silent errors, and make it easy to check each step programmatically.

Q45

What is long-running agent execution, and what challenges does it bring?

Agents that run for minutes or hours across many steps. Challenges include persisting state, recovering from crashes, staying within context limits, controlling cost, and keeping humans informed of progress.

Q46

What is an A2A or agent-to-agent protocol?

Emerging standards that let agents built by different teams or vendors discover each other, exchange tasks and messages, and collaborate through a common interface, much as MCP standardises tool access.

Q47

What business processes are good first agent projects?

Lead research and enrichment, support ticket triage and drafting, invoice and document processing, internal knowledge assistants, report generation and data entry across systems — tasks with clear inputs, outputs and reviewable results.

Q48

How do you measure business value from an agent?

Compare time saved per task, task completion rate, error rate, cost per task and user satisfaction against the manual baseline, and track how often humans must correct or take over.

Q49

What skills does an agentic AI engineer need?

Python, LLM APIs and prompting, tool and API design, RAG, state management, evaluation and testing, security thinking (permissions, prompt injection), observability, and an understanding of the business process being automated.

Q50

Explain agentic AI to a non-technical person.

"A normal AI chat answers your question. An AI agent is more like an assistant you give a goal to — it figures out the steps, uses apps and data to do them, checks its work, and asks you before doing anything important."

Member question bank

Topic-wise question sets, case studies and coding challenges you can download — for The Data School learners.

Prepare for interviews with a mentor

Mock interviews, project walkthroughs and question practice are part of every program at our KPHB, Kukatpally centre.

Chat on WhatsApp