PwC interview questions & answers

13 PwC interview questions with full model answers — Product & growth, Technical, Coding. Drawn from the same bank ChannelPulse drills from (13 PwC questions in total).

CodingEasyPwCData ScientistCoding screen

1. Can you explain how you would use Python lists and dictionaries to manage data in a data science project?

The full question

Can you explain how you would use Python lists and dictionaries to manage data in a data science project? Provide an example of how you might implement these structures.

Model answer

The flow

  1. Clarify inputs & output shape: Identify the data types and structures needed for the project.
  2. Brute force first: Implement a basic solution using Python lists and dictionaries.
  3. Optimize: Improve the efficiency of data manipulation and retrieval.
  4. State complexity: Analyze the time and space complexity of the solution.
  5. Test the edges: Ensure the solution handles edge cases and large datasets effectively.

The answer

1. Clarify inputs & output shape

  • For a data science project, you often deal with datasets that can be represented as lists of dictionaries, where each dictionary represents a data record with key-value pairs.
  • Example: A dataset of employees where each employee has attributes like name, age, and department.

2. Brute force first

  • Start by using lists to store multiple records and dictionaries to store attributes of each record.
# Example dataset of employees
employees = [
    {"name": "Alice", "age": 30, "department": "HR"},
    {"name": "Bob", "age": 25, "department": "Engineering"},
    {"name": "Charlie", "age": 35, "department": "Marketing"}
]

# Function to find employees in a specific department
def find_employees_by_department(employees, department):
    return [emp for emp in employees if emp["department"] == department]

# Example usage
hr_employees = find_employees_by_department(employees, "HR")
print(hr_employees)
  • Approach: Use a list comprehension to filter employees by department.

3. Optimize

  • If frequent lookups by department are needed, consider restructuring the data for faster access.
# Optimized data structure using a dictionary
employees_by_department = {
    "HR": [{"name": "Alice", "age": 30}],
    "Engineering": [{"name": "Bob", "age": 25}],
    "Marketing": [{"name": "Charlie", "age": 35}]
}

# Function to get employees by department
def get_employees_by_department(department):
    return employees_by_department.get(department, [])

# Example usage
hr_employees = get_employees_by_department("HR")
print(hr_employees)
  • Approach: Use a dictionary to map departments to lists of employees, improving lookup time.

4. State complexity

  • Time Complexity: Initial brute force approach has $O(n)$ time complexity for lookups, where $n$ is the number of employees. Optimized approach reduces lookup time to $O(1)$.
  • Space Complexity: Both approaches use $O(n)$ space, but the optimized approach may require additional space for the dictionary.

5. Test the edges

  • Test with an empty list, a single record, and a large dataset to ensure robustness.

Why this works

  • Interviewer is testing: Ability to use basic data structures effectively and optimize for efficiency.
  • Sanity check: Ensures the candidate understands how to structure data for common operations.
  • Weak answers: May overlook the need for optimization or fail to handle edge cases, leading to inefficient or incorrect solutions.
CodingEasyPwCSoftware Engineer

2. Roman to Integer (LeetCode)

Model answer

The task

Convert a string of Roman numeral symbols into its integer value. Roman numerals use a small set of symbols, with some smaller values placed before larger ones to indicate subtraction.

Key idea

Scan the string from left to right, comparing each symbol’s value with the next one. If the current value is smaller, subtract it; otherwise, add it. This handles subtractive pairs without needing to process them separately.

Approach

  1. Store the integer value for each Roman numeral symbol in a lookup table.
  2. Initialize a running total to zero.
  3. For each symbol, compare its value with the following symbol’s value, if one exists.
  4. Subtract the current value when it is smaller than the next value; otherwise, add it.
  5. Return the total. This assumes the input is a valid Roman numeral.
class Solution:
    def romanToInt(self, s: str) -> int:
        values = {
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000,
        }

        total = 0

        for i, symbol in enumerate(s):
            current = values[symbol]

            # A smaller value before a larger value is subtracted.
            if i + 1 < len(s) and current < values[s[i + 1]]:
                total -= current
            else:
                total += current

        return total

Complexity: Time: O(n), where n is the string length, since each symbol is visited once.

Complexity: Space: O(1), because the lookup table has a fixed number of entries.

Common follow-ups

  • How would you handle invalid Roman numeral strings? Validate symbol order and repetition rules before or during conversion.
  • How would you convert an integer to a Roman numeral? Greedily subtract from a descending list of allowed values, including subtractive pairs.
  • Can the conversion be done scanning right to left? Yes; subtract a value if it is smaller than the largest value already seen to its right, otherwise add it.
CodingEasyPwCSoftware Engineer

3. Two Sum (LeetCode)

Model answer

The task

Given a list of integers and a target, return the indices of two distinct elements whose values add up to the target. The usual version guarantees a valid pair.

Key idea

As we scan the list, store each value’s index in a hash table. For the current value, check whether its needed complement has already appeared; this finds a pair in one pass.

Approach

  1. Create a dictionary mapping previously seen values to their indices.
  2. For each element, compute the complement needed to reach the target.
  3. If that complement is in the dictionary, return its stored index and the current index.
  4. Otherwise, store the current value and index, then continue.
from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # Map each value already visited to its index.
        seen = {}

        for index, value in enumerate(nums):
            complement = target - value

            # A match must come from an earlier, distinct element.
            if complement in seen:
                return [seen[complement], index]

            seen[value] = index

        # The standard problem guarantees a solution.
        raise ValueError("No two elements sum to the target")

Complexity:

  • Time: O(n), where n is the number of elements; each lookup and insertion is O(1) on average.
  • Space: O(n), for the dictionary of values seen so far.

Common follow-ups

  • What if there may be multiple valid pairs? Return the first pair found, or keep searching and collect pairs according to the required output rules.
  • What if the input is sorted? Use two pointers from opposite ends for O(1) extra space; preserve original indices if those are required.
  • What if values repeat? The dictionary stores indices, and checking before insertion ensures the current element is not paired with itself.
CodingEasyPwCSoftware Engineer

4. Valid Palindrome (LeetCode)

Model answer

The task

Determine whether a string reads the same forward and backward after disregarding characters that are not letters or digits and treating uppercase and lowercase as equivalent.

Key idea

Compare characters from both ends, skipping anything that should be ignored. If every remaining pair matches, the string is a palindrome.

Approach

  1. Initialize pointers at the start and end of the string.
  2. Move the left pointer past non-alphanumeric characters.
  3. Move the right pointer past non-alphanumeric characters.
  4. Compare the lowercase forms of the characters at the pointers; return False if they differ.
  5. Move both pointers inward and continue. If they meet or cross, return True.
class Solution:
    def isPalindrome(self, s: str) -> bool:
        left, right = 0, len(s) - 1

        while left < right:
            # Ignore characters that are not letters or digits.
            while left < right and not s[left].isalnum():
                left += 1
            while left < right and not s[right].isalnum():
                right -= 1

            # Compare without regard to letter case.
            if s[left].lower() != s[right].lower():
                return False

            left += 1
            right -= 1

        return True

Complexity:

  • Time: O(n), where n is the string length; each pointer moves only inward.
  • Space: O(1), since the comparisons use no additional data structure.

Common follow-ups

  • What if the input contains no letters or digits? It is considered a palindrome, since there are no mismatching characters.
  • Can you avoid creating a normalized copy of the string? Yes; the two-pointer scan uses constant extra space.
  • How would you handle Unicode normalization? Normalize the string first if canonically equivalent characters should compare as equal; that may require additional space.
CodingEasyPwCSoftware Engineer

5. Longest Common Prefix (LeetCode)

Model answer

The task

Given a list of strings, return the longest string that is a prefix of every entry. If there is no shared prefix, return an empty string.

Key idea

Compare characters at the same position across all strings, starting from the first string. Stop at the first mismatch or when any string runs out.

Approach

  1. If the list is empty, return an empty string.
  2. Scan each character of the first string from left to right.
  3. For each position, compare that character with the character at the same position in every other string.
  4. If a string is too short or a character differs, return the matching prefix before that position.
  5. If all positions match, return the first string.
from typing import List

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""

        first = strs[0]

        for i, char in enumerate(first):
            for word in strs[1:]:
                if i == len(word) or word[i] != char:
                    return first[:i]

        return first

Complexity:

  • Time: O(S), where S is the total number of characters inspected.
  • Space: O(1) auxiliary space, excluding the returned prefix.

Common follow-ups

  • How would you handle many prefix queries over the same set of strings? Build a trie once, then traverse it to find shared prefixes.
  • Could sorting help? Yes. Sort the strings and compare only the first and last; their common prefix is shared by all strings.
  • What if strings arrive as a stream? Keep a running prefix and shorten it as each new string arrives.
CodingMediumPwCSoftware Engineer

6. Next Permutation (LeetCode)

Model answer

The task

Rearrange the array in place to produce the next lexicographically greater ordering of its values. If no greater ordering exists, wrap around to the smallest ordering.

Key idea

The suffix after the rightmost position where the sequence increases is in descending order, so it is already the largest arrangement of those values. Swap that position with the smallest value in the suffix that is still larger, then reverse the suffix to make it as small as possible.

Approach

  1. Scan from right to left to find the rightmost index whose value is smaller than the value after it.
  2. If such an index exists, scan from the end to find the rightmost value larger than the pivot, then swap them.
  3. Reverse the portion after the pivot. This also handles the case where no pivot exists: the whole array becomes ascending.
  4. Mutate the input list directly.
from typing import List

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        n = len(nums)

        # Find the rightmost position that can be increased.
        pivot = n - 2
        while pivot >= 0 and nums[pivot] >= nums[pivot + 1]:
            pivot -= 1

        if pivot >= 0:
            # The suffix is descending; its rightmost value greater
            # than the pivot is the smallest value that can replace it.
            successor = n - 1
            while nums[successor] <= nums[pivot]:
                successor -= 1

            nums[pivot], nums[successor] = nums[successor], nums[pivot]

        # Reverse the suffix to make it the smallest possible ordering.
        left, right = pivot + 1, n - 1
        while left < right:
            nums[left], nums[right] = nums[right], nums[left]
            left += 1
            right -= 1

Complexity:

  • Time: O(n), with a constant number of linear scans.
  • Space: O(1), since the rearrangement is done in place.

Common follow-ups

  • Why choose the rightmost pivot? It preserves the longest possible prefix, making the next ordering as close as possible.
  • How are duplicate values handled? The strict comparisons skip equal values and still select the correct next ordering.
  • What if the input is already in descending order? No pivot exists, so reversing the full array produces the smallest ordering.
  • How would you return a new list instead? Copy the input first, then apply the same in-place algorithm to the copy.
CodingMediumPwCSoftware Engineer

7. Valid Parenthesis String (LeetCode)

Model answer

The task

Given a string containing (, ), and *, decide whether the * characters can be interpreted so the resulting parentheses are balanced. Each * may represent an opening parenthesis, a closing parenthesis, or nothing.

Key idea

Track the range of possible counts of unmatched opening parentheses after each character. The lowest count assumes stars close parentheses when possible; the highest assumes stars open them. If the highest count becomes negative, no interpretation can work.

Approach

  1. Initialize the minimum and maximum possible unmatched opening counts to zero.
  2. For (, increment both counts.
  3. For ), decrement both counts.
  4. For *, decrement the minimum and increment the maximum.
  5. Clamp the minimum to zero, since unmatched openings cannot be negative.
  6. Reject if the maximum is negative; after scanning, accept only if the minimum is zero.
class Solution:
    def checkValidString(self, s: str) -> bool:
        # Range of possible unmatched opening-parenthesis counts.
        low = 0
        high = 0

        for ch in s:
            if ch == "(":
                low += 1
                high += 1
            elif ch == ")":
                low -= 1
                high -= 1
            else:  # "*" may be "(", ")", or empty
                low -= 1
                high += 1

            # No interpretation can have fewer than zero unmatched opens.
            low = max(low, 0)

            # Even interpreting every star as "(" cannot fix this prefix.
            if high < 0:
                return False

        # A valid interpretation must be able to leave no unmatched opens.
        return low == 0

Complexity:

  • Time: O(n), where n is the string length; each character is processed once.
  • Space: O(1), using only two counters.

Common follow-ups

  • How would you return one valid interpretation? Track choices or use a stack of parenthesis and star indices, then match remaining openings with later stars.
  • Can dynamic programming solve it? Yes; track reachable balance counts, though it uses O(n²) time and O(n) space.
  • What if there are multiple wildcard types with different allowed meanings? Update the reachable balance range or use a more general DP if the possible balances are not contiguous.
CodingMediumPwCSoftware Engineer

8. Longest Substring Without Repeating Characters (LeetCode)

Model answer

The task

Find the length of the longest contiguous section of a string in which every character appears at most once.

Key idea

Maintain a sliding window with no repeated characters. When a character repeats within the window, move the left edge just past its previous occurrence.

Approach

  1. Track each character’s most recent index in a dictionary.
  2. Keep left as the window’s starting index and best as its longest length so far.
  3. For each character, move left forward if its previous occurrence is inside the current window.
  4. Record the character’s current index and update best using the window length.
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        last_seen = {}
        left = 0
        best = 0

        for right, char in enumerate(s):
            # Skip past a repeated character if it is in the current window.
            if char in last_seen and last_seen[char] >= left:
                left = last_seen[char] + 1

            last_seen[char] = right
            best = max(best, right - left + 1)

        return best

Complexity:

  • Time: O(n), because each character is processed once.
  • Space: O(k), where k is the number of distinct characters encountered.

Common follow-ups

  • Return the substring itself: store the best window’s start and end indices when updating best.
  • Handle a stream of characters: keep the same window state and process each arriving character incrementally.
  • Use a fixed-size character set: replace the dictionary with an array of last-seen indices.
Product & growthMediumPwCData ScientistAnalytics / experimentation round

9. What’s the difference between A/A and A/B tests?

Model answer

The flow

  1. Define the Hypothesis & Metrics: Clearly articulate the purpose of the test and the metrics to be measured.
  2. Determine Unit of Randomization: Decide on the level at which randomization will occur (e.g., user, session).
  3. Calculate Power & Sample Size: Ensure the test is statistically powered to detect meaningful differences.
  4. Run the Test & Guard Against Peeking: Execute the test while avoiding biases from early data peeking.
  5. Analyze Results with Guardrails: Interpret results with statistical rigor and predefined guardrails.

The answer

Hypothesis & Metrics

  • A/A Testing: The hypothesis is that there should be no significant difference between the two groups as both are exposed to the same variant (control).
  • A/B Testing: The hypothesis is that the new variant (B) will perform better than the control (A) on predefined metrics, such as conversion rate.

Unit of Randomization

  • Both tests typically randomize at the user level to ensure each user is only exposed to one variant.

Power & Sample Size

  • A/A Testing: Used to validate the experimental setup, ensuring randomization and measurement are correct. Sample size should be large enough to detect any unexpected differences.
  • A/B Testing: Sample size is calculated based on the expected effect size, power, and significance level to detect meaningful differences.

Run the Test & Guard Against Peeking

  • A/A Testing: Run to completion to validate the test setup without expecting any differences.
  • A/B Testing: Run until the predetermined sample size is reached, avoiding interim analysis to prevent biases.

Analyze Results with Guardrails

  • A/A Testing: Check for any significant differences; if found, investigate potential issues in randomization or measurement.
  • A/B Testing: Analyze the results using statistical tests to determine if the observed differences are significant, ensuring guardrails like confidence intervals are respected.

Why this works

  • Understanding of Purpose: The interviewer is testing the candidate's understanding of the purpose and application of A/A versus A/B tests.
  • Validation of Setup: A strong answer highlights how A/A tests validate the experimental setup, ensuring the reliability of subsequent A/B tests.
  • Statistical Rigor: Emphasizes the importance of statistical rigor in both types of tests, including proper sample size calculation and avoiding peeking.
  • Common Pitfalls: Weak answers may confuse the purposes of A/A and A/B tests or fail to address the importance of validating the test environment with A/A testing.
Product & growthHardPwCManagement ConsultantCase interview

10. What are the reasons for the profitability decrease of the auto manufacturer?

Model answer

The flow

  1. Define the problem: Clarify the scope of the profitability decrease.
  2. Break down profit: Use the formula $\text{Profit} = \text{Revenue} - \text{Cost}$.
  3. Analyze revenue: Examine components like price, volume, and mix.
  4. Analyze costs: Split into fixed and variable costs, then delve deeper.
  5. Identify drivers: Isolate specific drivers affecting revenue or cost.
  6. Recommend solutions: Propose actions to address identified issues.

The answer

Define the problem: We need to understand why the auto manufacturer's profitability has decreased. This involves examining both revenue and cost components.

Break down profit: Profit is calculated as $\text{Revenue} - \text{Cost}$. We will analyze both sides to identify the issue.

Analyze revenue:

  • Price: Check if there have been any changes in the pricing strategy or competitive pricing pressures.
  • Volume: Investigate if there is a drop in the number of units sold, potentially due to market demand or competition.
  • Mix: Assess if the product mix has shifted towards lower-margin products.

Analyze costs:

  • Fixed Costs: Examine if there have been increases in overheads, such as rent or salaries.
  • Variable Costs: Look into raw material costs, labor costs per unit, and any inefficiencies in production.

Identify drivers:

  • Revenue Drivers: Suppose the analysis shows a 10% drop in sales volume due to increased competition and a 5% decrease in average selling price due to aggressive discounting.
  • Cost Drivers: Assume a 15% increase in raw material costs due to supply chain disruptions and a 10% rise in labor costs because of overtime pay.

Recommend solutions:

  • Revenue: Consider revising the pricing strategy to better compete, enhancing marketing efforts to boost sales volume, and optimizing the product mix.
  • Costs: Negotiate better terms with suppliers, streamline production processes to reduce overtime, and explore automation to cut labor costs.

Why this works

  • Holistic Analysis: The interviewer is assessing the candidate's ability to dissect a problem into its core components and analyze each systematically.
  • Data-Driven Insights: Strong answers rely on plausible data to support hypotheses, demonstrating analytical rigor.
  • Actionable Recommendations: A strong candidate offers concrete solutions, not just identifies problems, showing practical business acumen.
  • Common Pitfalls: Weak answers might focus too narrowly on one area (e.g., only revenue) or fail to provide actionable recommendations, missing the broader business context.
TechnicalEasyPwCData ScientistTechnical screen

11. Facebook has a content team that labels pieces of content on the platform as spam or not spam.

The full question

Facebook has a content team that labels pieces of content on the platform as spam or not spam. 90% of them are diligent raters and will label 20% of the content as spam and 80% as non-spam. The remaining 10% are non-diligent raters and will label 0% of the content as spam and 100% as non-spam. Assume the pieces of content are labeled independently from one another, for every rater. Given that a rater has labeled 4 pieces of content as good, what is the probability that they are a diligent rater?

Model answer

The flow

  1. Identify the distributions: Recognize the problem as a Bayesian probability question.
  2. Write the formula: Use Bayes' Theorem to calculate the desired probability.
  3. Compute the likelihoods: Calculate the probability of the observed data given each type of rater.
  4. Apply Bayes' Theorem: Substitute the known probabilities into the formula.
  5. Compute the posterior probability: Solve for the probability that the rater is diligent given the observed data.
  6. Interpret the result: Discuss implications and limitations of the result.

The answer

1. Identify the distributions

  • We have two types of raters: diligent and non-diligent.
  • Diligent raters label 20% as spam and 80% as non-spam.
  • Non-diligent raters label 0% as spam and 100% as non-spam.

2. Write the formula

  • We use Bayes' Theorem: $$ P(D | G) = \frac{P(G | D) \cdot P(D)}{P(G)} $$ where:
  • $P(D | G)$ is the probability that the rater is diligent given 4 pieces labeled as good.
  • $P(G | D)$ is the probability of labeling 4 pieces as good given the rater is diligent.
  • $P(D)$ is the prior probability of a rater being diligent.
  • $P(G)$ is the total probability of labeling 4 pieces as good.

3. Compute the likelihoods

  • $P(G | D) = (0.8)^4 = 0.4096$
  • $P(G | \neg D) = (1)^4 = 1$

4. Apply Bayes' Theorem

  • $P(D) = 0.9$, the probability of a rater being diligent.
  • $P(\neg D) = 0.1$, the probability of a rater being non-diligent.
  • $P(G) = P(G | D) \cdot P(D) + P(G | \neg D) \cdot P(\neg D)$ $$ P(G) = 0.4096 \cdot 0.9 + 1 \cdot 0.1 = 0.46864 $$

5. Compute the posterior probability

  • Substitute into Bayes' Theorem: $$ P(D | G) = \frac{0.4096 \cdot 0.9}{0.46864} \approx 0.786 $$

6. Interpret the result

  • The probability that the rater is diligent given they labeled 4 pieces as good is approximately 78.6%.
  • This high probability suggests that labeling all pieces as good is more likely done by a diligent rater.
  • The assumption of independence and the specific labeling behavior of raters are crucial for this result.

Why this works

  • Testing Bayesian reasoning: The question assesses understanding of Bayes' Theorem and its application.
  • Sanity check: A strong answer checks the reasonableness of the result (e.g., high probability aligns with diligent behavior).
  • Common pitfalls: Weak answers might ignore the prior probabilities or miscalculate likelihoods, leading to incorrect conclusions.
  • Assumptions clarity: A strong answer clearly states assumptions, like independence of labels and fixed rater behavior.
TechnicalMediumPwCData ScientistML round

12. Describe how you evaluate the performance of a machine learning model.

The full question

Describe how you evaluate the performance of a machine learning model. Can you give an example of how you’ve applied these evaluation techniques in a past project?

Model answer

The flow

  1. Frame the problem: Define the business problem and the desired outcome.
  2. Features & baseline: Identify key features and establish a baseline model for comparison.
  3. Model choice and why: Select the appropriate model(s) based on the problem type and data characteristics.
  4. Metric that matches the cost of errors: Choose the evaluation metric that aligns with business goals.
  5. Overfitting checks: Implement techniques to detect and mitigate overfitting.
  6. Iterate and refine: Continuously improve the model based on evaluation results.

The answer

Frame the problem: In a previous project, I worked on predicting customer churn for a subscription-based service. The goal was to identify customers at risk of leaving so that the marketing team could intervene with retention strategies.

Features & baseline: I identified features such as usage frequency, customer service interactions, and payment history. I established a baseline using a simple logistic regression model to predict churn, which provided a benchmark for improvement.

Model choice and why: Given the binary nature of the problem, I considered models like decision trees, random forests, and gradient boosting machines. I chose a random forest model due to its ability to handle non-linear relationships and interactions between features effectively.

Metric that matches the cost of errors: Since the cost of false negatives (failing to identify a churn risk) was higher than false positives (unnecessarily targeting a non-churn customer), I used the F1-score as the primary evaluation metric. This metric balances precision and recall, focusing on minimizing false negatives.

Overfitting checks: To prevent overfitting, I used cross-validation and monitored the model's performance on a validation set. I also employed techniques such as feature selection and regularization.

Iterate and refine: After evaluating the model, I iteratively refined it by tuning hyperparameters and testing additional features. The final model achieved an F1-score of 0.85, significantly improving the baseline.

Why this works

  • Testing understanding: The interviewer is assessing the candidate's ability to apply a structured approach to model evaluation.
  • Sanity check: A strong answer should mention the importance of aligning metrics with business objectives, demonstrating a practical understanding of model evaluation.
  • Weak answers: Candidates may fail by not considering the business context or by choosing inappropriate metrics, which can lead to suboptimal model performance.
TechnicalMediumPwCData ScientistML round

13. How do you decide which machine learning model to use for a specific problem?

The full question

How do you decide which machine learning model to use for a specific problem? For instance, how would you approach a dataset predicting customer churn?

Model answer

The flow

  1. Frame the problem → Define the objective and type of problem (e.g., classification for churn prediction).
  2. Features & baseline → Identify features and establish a baseline model (e.g., logistic regression).
  3. Model choice and why → Select models based on problem type and data characteristics.
  4. Metric that matches the cost of errors → Choose evaluation metrics that align with business costs (e.g., precision, recall).
  5. Overfitting checks → Implement techniques to detect and mitigate overfitting (e.g., cross-validation).

The answer

1. Frame the problem:

  • The objective is to predict customer churn, which is a binary classification problem.
  • We want to identify customers likely to leave a service, allowing for targeted retention strategies.

2. Features & baseline:

  • Identify features such as customer demographics, usage patterns, and interaction history.
  • Use a simple logistic regression model as a baseline to understand the problem.
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# Sample data preparation
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Baseline model
baseline_model = LogisticRegression()
baseline_model.fit(X_train, y_train)
y_pred = baseline_model.predict(X_test)

# Evaluate baseline
baseline_accuracy = accuracy_score(y_test, y_pred)
print(f"Baseline Accuracy: {baseline_accuracy}")

3. Model choice and why:

  • Consider models like decision trees, random forests, or gradient boosting for better handling of non-linear relationships and interactions.
  • Random forests are robust to overfitting and can handle a large number of features.

4. Metric that matches the cost of errors:

  • Use precision and recall to evaluate the model, as false positives and false negatives have different business costs.
  • For churn prediction, recall might be prioritized to ensure most potential churners are identified.

5. Overfitting checks:

  • Implement cross-validation to ensure model generalization.
  • Use techniques like regularization or pruning for complex models.
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score

# Random Forest model
rf_model = RandomForestClassifier(n_estimators=100, random_state=42)
cv_scores = cross_val_score(rf_model, X_train, y_train, cv=5, scoring='recall')
print(f"Cross-validated Recall: {cv_scores.mean()}")

Why this works

  • Problem framing: Clearly defining the problem helps in choosing the right model type and evaluation metrics.
  • Baseline model: Establishing a baseline provides a reference point to measure improvements.
  • Model choice: Selecting models based on data characteristics and problem requirements ensures better performance.
  • Error cost alignment: Using metrics that reflect business priorities ensures the model's utility aligns with business goals.
  • Overfitting checks: Implementing cross-validation and regularization ensures the model performs well on unseen data, preventing overfitting.
  • Weak answers: Often fail to align metrics with business goals or neglect overfitting checks, leading to models that are either not useful or not generalizable.

Practice these out loud, don't memorise them

Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.

Get ChannelPulse Browse all questions