Meta interview questions & answers

20 real Meta interview questions with full model answers — Behavioral, Technical, Coding, System design. Drawn from the same verified bank ChannelPulse drills from (2178 Meta questions in total).

BehavioralEasyMetaEngineering Manager

1. What motivates you as an engineering manager?

Model answer

Situation

As an engineering manager at my previous company, I was responsible for leading a team of software engineers working on a critical project that involved developing a new feature for our flagship product. This project was high-stakes because it was expected to significantly enhance user engagement and drive revenue growth. My role was pivotal in ensuring that the team delivered high-quality work on time while fostering a culture of continuous improvement and professional growth.

Task

My primary goal was to motivate and guide the team to not only meet the project deadlines but also to elevate their skills and performance. A key challenge was balancing the immediate demands of the project with the long-term development of the team members.

Action

  • I began by setting clear, achievable goals for the team, aligning them with both the project objectives and individual career aspirations. This alignment helped each team member see how their work contributed to the broader company goals, enhancing their motivation.
  • To foster a culture of development, I implemented regular one-on-one coaching sessions. During these sessions, I provided constructive feedback and identified stretch opportunities for each team member, encouraging them to take on new challenges and responsibilities.
  • I facilitated knowledge-sharing sessions where team members could present their work and learn from each other. This not only improved technical skills but also built a sense of community and collaboration within the team.
  • Recognizing the importance of work-life balance, I advocated for flexible work arrangements, which helped maintain high morale and productivity.
  • I also focused on creating a psychologically safe environment where team members felt comfortable sharing ideas and concerns. This openness led to innovative solutions and a more cohesive team dynamic.

Result

As a result of these efforts, the team successfully delivered the project on schedule with high quality. The feature launch exceeded user engagement targets, contributing to a notable increase in revenue. Additionally, the team's performance improved significantly, with several members receiving promotions or taking on more advanced roles. This experience reinforced my belief in the power of investing in people and the importance of balancing immediate project needs with long-term talent development. I learned that as a manager, my success is measured by the growth and achievements of my team.

BehavioralEasyMetaProduct AnalystOnsite

2. Tell me about a high-impact project that you personally drove end-to-end.

The full question

Tell me about a high-impact project that you personally drove end-to-end.

Walk through the full lifecycle and be ready to cover each of the following:

  1. Problem & why it mattered — the business problem, the user impact and business impact, and the baseline metric or pain point that made it urgent.
  2. Your role & scope — what you personally owned versus influenced, the decisions you were accountable for, and how you scoped ambiguous work.
  3. Success definition & metrics — what success looked like, the primary metric(s) plus guardrails you defined, and how you tracked them.
  4. Analysis & experimentation — how you diagnosed the problem with data, validated instrumentation, sized the opportunity, and what analytical or experimentation methods you used.
  5. Cross-functional partnership — which stakeholders you worked with (PM, Engineering, Design, Data Science, Marketing, Legal, Ops) and how you handled disagreement or competing priorities.
  6. Trade-offs & obstacles — the major trade-offs you made, the biggest obstacle you faced, and how you managed constraints (time, eng bandwidth, policy, quality).
  7. Implementation & launch — what you personally built or implemented, how you drove launch readiness, and how you rolled out (A/B test, pilot, or phased rollout).
  8. Measurement & outcome — the quantified result, the timeframe, whether the impact was statistically significant and sustained, and how broadly it shipped.
  9. Reflection — what you learned and what you would do differently in retrospect.

Model answer

Situation

At Meta, I was a product manager responsible for enhancing user engagement on our social media platform. Our team identified a significant drop in user interaction with video content, which was crucial for our ad revenue model. The baseline metric showed a 15% decline in video views over the past quarter, impacting both user retention and advertiser satisfaction.

Task

My goal was to reverse the declining trend in video engagement by implementing a feature that would increase video views by at least 20% within six months. The challenge was to design a solution that was both technically feasible and aligned with user experience expectations.

Action

  • I conducted a thorough analysis of user behavior data to identify patterns and potential causes for the decline. This involved collaborating with the data science team to validate our instrumentation and ensure data accuracy.
  • Based on insights, I proposed an algorithm-driven recommendation system to surface personalized video content to users. I scoped the project by defining clear success metrics, including increased video views and user session duration.
  • I worked closely with engineering and design teams to develop a prototype. We prioritized a lean MVP approach to test the core functionality quickly.
  • To ensure alignment, I facilitated cross-functional meetings with stakeholders from marketing, legal, and operations to address any concerns and gather feedback.
  • We faced a major trade-off between speed and quality, as engineering resources were limited. I decided to focus on a phased rollout, allowing us to gather real-time feedback and iterate rapidly.

Result

The project led to a 25% increase in video views within four months, surpassing our initial target. The phased rollout strategy allowed us to address minor issues before a full-scale launch, ensuring a smooth user experience. The feature was well-received, with positive feedback from both users and advertisers. This experience reinforced the value of data-driven decision-making and cross-functional collaboration.

Reflection

I learned the importance of balancing ambition with feasibility, especially when resources are constrained. In retrospect, I would have involved the marketing team earlier to better align our messaging strategy with the feature launch. This project taught me the critical role of iterative development and stakeholder management in driving impactful results.

BehavioralEasyMetaEngineering Manager

3. Describe a project you have worked on.

Model answer

Situation

A project I often use as an example is consolidating several teams' synchronous notification implementations into a shared delivery platform. Each product team had built its own provider integrations and retry behavior. That meant users received inconsistent notifications, provider outages created request-path failures, and engineers repeatedly solved the same operational problems. I was the engineering manager for the team asked to deliver the platform while continuing to support existing product work.

Task

I owned getting the teams to a common architecture and migrating the first high-volume use cases without interrupting delivery. The main tension was between building a reusable platform and shipping visible product improvements quickly; a full rewrite would have been too risky and too slow.

Action

  • I began with a short discovery phase: mapped existing event flows, interviewed product and support teams, and established baseline measures for delivery success, latency, and incident volume.
  • I aligned product leads on a narrow first milestone: standardize event intake and push delivery for two use cases, while leaving lower-volume channels and complex preferences for later.
  • I worked with senior engineers to define a versioned event contract, idempotency behavior, bounded retries, and a queue-based architecture. We chose asynchronous delivery so provider slowness would not block product requests, accepting that delivery would be eventually consistent.
  • I split ownership into platform, migration, and operations workstreams, assigned a directly responsible engineer to each, and resolved disagreements through explicit decision records rather than repeated design meetings.
  • I required a shadow period, canary rollout, dashboards, and rollback criteria. We compared delivery outcomes from the new and old paths before moving traffic, and kept a compatibility adapter so product teams did not need a coordinated release.

Result

The first two use cases moved without a customer-facing outage, and the shared path improved delivery success from 96% to 99% while reducing provider-related request errors to near zero. Three teams adopted the event contract over the following quarter, reducing duplicated integration maintenance. I learned to treat migration and adoption as part of the product: a technically sound platform only creates value when teams can move incrementally and operate it confidently.

BehavioralEasyMetaProduct AnalystTechnical Screen

4. A Head of Product asks: Pick one analytics/data science project you led end-to-end.

The full question

A Head of Product asks:

  1. Pick one analytics/data science project you led end-to-end.
  2. What was the product problem and why did it matter?
  3. What metrics did you choose, and what trade-offs did you consider (primary vs guardrails)?
  4. What analysis or experiment did you run, and how did you ensure the result was credible?
  5. What was the impact (quantified), what did you ship/decide, and what would you do differently?

Answer in a structured way (you can use STAR/CAR).

Model answer

Situation

In my role as a data scientist at a leading tech company, I was tasked with leading an analytics project aimed at improving user engagement on our social media platform. The platform had seen a decline in active user sessions, which was a critical metric for our business as it directly impacted ad revenue. The stakes were high because maintaining user engagement was essential for our competitive edge and financial performance.

Task

My specific goal was to identify and implement data-driven strategies to enhance user engagement. The key constraint was to ensure that any changes would not negatively impact user experience or platform stability. I needed to balance between driving engagement and maintaining a seamless user experience.

Action

  • I began by conducting a comprehensive analysis of user behavior data to identify patterns and potential areas for improvement. This involved segmenting users based on activity levels and engagement metrics.
  • I selected key metrics to track, such as session duration and interaction frequency, while also considering guardrail metrics like user churn and system load to ensure we didn't compromise on user experience or platform performance.
  • To test hypotheses, I designed and ran A/B tests on different features, such as personalized content recommendations and notification frequency adjustments. I ensured the credibility of results by using statistically significant sample sizes and controlling for external variables.
  • I collaborated closely with the product and engineering teams to iterate on feature designs based on test outcomes, ensuring alignment with our overall product strategy and technical feasibility.
  • Throughout the project, I maintained clear communication with stakeholders, presenting data-driven insights and recommendations to guide decision-making.

Result

The project led to a 15% increase in user session duration and a 10% rise in interaction frequency, significantly boosting our engagement metrics. These improvements contributed to a 5% increase in ad revenue over the following quarter. Reflecting on the project, I learned the importance of balancing innovation with user-centric design and the value of cross-functional collaboration. If I were to do it differently, I would invest more time in user interviews to complement quantitative data with qualitative insights, enhancing our understanding of user needs.

CodingEasyMetaSoftware EngineerTechnical Screen

5. You are asked to solve two separate coding questions.

The full question

You are asked to solve two separate coding questions. You do not need to run code; be prepared to explain your approach and walk through examples.

Question 1: Near-palindrome with one deletion

Given a string s, determine whether it can become a palindrome after deleting at most one character.

  • Input: a string s (consisting of lowercase English letters)
  • Output: true if s can be made a palindrome by removing 0 or 1 character; otherwise false
  • Constraints (typical): 1 <= len(s) <= 1e5

Example:

  • s = "abca" → true (delete 'b' or 'c')
  • s = "abc" → false

Question 2: Binary tree vertical order traversal

Given the root of a binary tree, return its vertical order traversal.

Define a node’s column as follows:

  • Root is at column 0
  • Left child is column col - 1
  • Right child is column col + 1

Return a list of columns from leftmost to rightmost. Within each column, list nodes in top-to-bottom order. If multiple nodes share the same row and column, order them in the same order they would appear in a level-order (BFS) traversal from left to right.

  • Input: root of a binary tree
  • Output: List[List[int]] (values grouped by column)
  • Constraints (typical): up to 1e4–1e5 nodes

Example: For the tree:

  • 3 as root
  • left child 9, right child 8
  • 9 has children 4 and 0
  • 8 has children 1 and 7

Vertical order output:

  • [[4], [9], [3, 0, 1], [8], [7]]

Explain your algorithm and its time/space complexity.

Model answer

// Question 1: Near-palindrome with one deletion
function validPalindrome(s) {
    function isPalindrome(l, r) {
        while (l < r) {
            if (s[l] !== s[r]) return false;
            l++;
            r--;
        }
        return true;
    }

    let left = 0;
    let right = s.length - 1;

    while (left < right) {
        if (s[left] !== s[right]) {
            // Try removing one character from either end
            return isPalindrome(left + 1, right) || isPalindrome(left, right - 1);
        }
        left++;
        right--;
    }
    return true;
}

// Approach for Question 1:
// - Use two pointers to check if the string is a palindrome.
// - If a mismatch is found, check if removing one of the mismatched characters results in a palindrome.
// - This is done by checking two substrings: one excluding the left character and one excluding the right character.

// Complexity for Question 1:
// Time: O(n), where n is the length of the string, as we may need to check the entire string.
// Space: O(1), as we use a constant amount of extra space.


// Question 2: Binary tree vertical order traversal
function verticalOrder(root) {
    if (!root) return [];

    const columnTable = new Map();
    const queue = [{ node: root, col: 0 }];
    let minCol = 0, maxCol = 0;

    while (queue.length > 0) {
        const { node, col } = queue.shift();

        if (!columnTable.has(col)) {
            columnTable.set(col, []);
        }
        columnTable.get(col).push(node.val);

        if (node.left) {
            queue.push({ node: node.left, col: col - 1 });
            minCol = Math.min(minCol, col - 1);
        }
        if (node.right) {
            queue.push({ node: node.right, col: col + 1 });
            maxCol = Math.max(maxCol, col + 1);
        }
    }

    const result = [];
    for (let i = minCol; i <= maxCol; i++) {
        result.push(columnTable.get(i));
    }
    return result;
}

// Approach for Question 2:
// - Use a BFS approach to traverse the tree while keeping track of the column index for each node.
// - Store nodes in a map where keys are column indices and values are lists of node values.
// - Track the minimum and maximum column indices to determine the range of columns to output.
// - Collect results from the map in order from the smallest to the largest column index.

// Complexity for Question 2:
// Time: O(n), where n is the number of nodes in the tree, as each node is processed once.
// Space: O(n), for the map and queue used to store nodes and their column indices.
CodingEasyMetaSoftware Engineer

6. Fruits Into Baskets II (LeetCode)

Model answer

The task

Process fruit quantities in order, assigning each to the leftmost unused basket whose capacity is large enough. Count how many fruit types cannot be assigned.

Key idea

Store the maximum capacity in each segment of a segment tree. This lets us find the leftmost basket that fits a fruit and mark that basket as used in logarithmic time.

Approach

  1. Build a segment tree whose leaves hold basket capacities and whose internal nodes hold the maximum capacity in their range.
  2. For each fruit, check whether the tree’s maximum capacity is sufficient.
  3. If it is, descend the tree, preferring the left child whenever it can fit the fruit.
  4. Mark the chosen basket as used and update the maxima on the path back up.
  5. Count fruits for which no basket is available.
from typing import List

class Solution:
    def numOfUnplacedFruits(
        self, fruits: List[int], baskets: List[int]
    ) -> int:
        n = len(baskets)
        if n == 0:
            return len(fruits)

        tree = [0] * (4 * n)

        def build(node: int, left: int, right: int) -> None:
            if left == right:
                tree[node] = baskets[left]
                return

            mid = (left + right) // 2
            build(node * 2, left, mid)
            build(node * 2 + 1, mid + 1, right)
            tree[node] = max(tree[node * 2], tree[node * 2 + 1])

        def take_leftmost(node: int, left: int, right: int, need: int) -> int:
            if left == right:
                tree[node] = 0  # This basket is now used.
                return left

            mid = (left + right) // 2
            if tree[node * 2] >= need:
                index = take_leftmost(node * 2, left, mid, need)
            else:
                index = take_leftmost(node * 2 + 1, mid + 1, right, need)

            tree[node] = max(tree[node * 2], tree[node * 2 + 1])
            return index

        build(1, 0, n - 1)

        unplaced = 0
        for amount in fruits:
            if tree[1] < amount:
                unplaced += 1
            else:
                take_leftmost(1, 0, n - 1, amount)

        return unplaced

Complexity:

  • Time: O(n + m log n), where n is the number of baskets and m is the number of fruits.
  • Space: O(n) for the segment tree.

Common follow-ups

  • What if baskets can be reused? Do not remove a basket after assignment; each fruit can independently check for a fitting capacity.
  • What if we need to report the chosen basket for each fruit? Record the returned index from the tree descent.
  • Could a simple scan work? Yes, it takes O(nm) in the worst case and may be adequate for small inputs.
CodingEasyMetaSoftware Engineer

7. Subtree of Another Tree (LeetCode)

Model answer

The task

Determine whether one binary tree occurs in another as a subtree: both the node values and the tree structure must match.

Key idea

Serialize each tree in preorder, recording a marker for every missing child. These markers preserve structure, so the smaller tree is a subtree exactly when its serialization appears contiguously in the larger tree’s serialization. Use KMP to search in linear time.

Approach

  1. Treat an empty candidate tree as a subtree.
  2. Serialize each tree in preorder, using None to represent missing nodes.
  3. Build the KMP prefix table for the candidate serialization.
  4. Scan the larger serialization with KMP and return whether the candidate is found.
class Solution:
    def isSubtree(self, root, subRoot):
        if subRoot is None:
            return True

        def serialize(node):
            tokens = []

            def visit(current):
                if current is None:
                    tokens.append(None)
                    return

                tokens.append(current.val)
                visit(current.left)
                visit(current.right)

            visit(node)
            return tokens

        text = serialize(root)
        pattern = serialize(subRoot)

        # Build the KMP prefix table.
        prefix = [0] * len(pattern)
        matched = 0

        for i in range(1, len(pattern)):
            while matched and pattern[i] != pattern[matched]:
                matched = prefix[matched - 1]

            if pattern[i] == pattern[matched]:
                matched += 1
                prefix[i] = matched

        # Search for the candidate serialization.
        matched = 0
        for token in text:
            while matched and token != pattern[matched]:
                matched = prefix[matched - 1]

            if token == pattern[matched]:
                matched += 1
                if matched == len(pattern):
                    return True

        return False

Complexity:

  • Time: O(n + m), where n and m are the numbers of nodes in the two trees.
  • Space: O(n + m) for the serialized tokens and KMP prefix table.

Common follow-ups

  • Can this be done without serialization? Try matching the candidate at every node; the worst case is O(nm).
  • What if many subtree queries use the same main tree? Cache a structural hash for each node, then verify matches to guard against collisions.
  • How do you avoid recursion-depth issues on skewed trees? Serialize iteratively with an explicit stack.
CodingEasyMetaSoftware Engineer

8. Defuse the Bomb (LeetCode)

Model answer

The task

For each position in a circular array, compute the sum of the next k values when k is positive, or the previous |k| values when k is negative. When k is zero, every result is zero.

Key idea

Maintain the sum of the relevant circular window and update it as the position advances, rather than recalculating each sum. Split |k| into complete cycles and a remainder so the solution also handles values of k larger than the array length.

Approach

  1. Return an empty list for an empty array, and zeros when k is zero.
  2. Split |k| into complete cycles and a remainder; each complete cycle contributes the array’s total sum.
  3. Initialize the remainder window: start after the current position for positive k, or before it for negative k.
  4. Record each result and slide the window by removing the value that leaves and adding the next value.
from typing import List

class Solution:
    def decrypt(self, code: List[int], k: int) -> List[int]:
        n = len(code)
        if n == 0:
            return []
        if k == 0:
            return [0] * n

        count = abs(k)
        cycles, remainder = divmod(count, n)
        full_cycle_sum = cycles * sum(code)
        result = [0] * n

        if k > 0:
            # Initial window contains the next `remainder` values.
            window = sum(code[j % n] for j in range(1, remainder + 1))

            for i in range(n):
                result[i] = full_cycle_sum + window
                # Advance the window to the next position.
                window -= code[(i + 1) % n]
                window += code[(i + remainder + 1) % n]
        else:
            # Initial window contains the previous `remainder` values.
            window = sum(code[-j % n] for j in range(1, remainder + 1))

            for i in range(n):
                result[i] = full_cycle_sum + window
                # Advance the window to the next position.
                window -= code[(i - remainder) % n]
                window += code[i % n]

        return result

Complexity:

  • Time: O(n), since each window is initialized and updated in constant time per position.
  • Space: O(n) for the result; O(1) auxiliary space.

Common follow-ups

  • What if k is zero? Return an array of zeros.
  • What if |k| exceeds the array length? Count full cycles separately, as above.
  • Can the result be produced in place? Only if modifying the input is allowed and its original values remain available during computation.
Product & growthEasyMetaData Science ManagerBusiness/Product Sense

9. How can data science help a business?

Model answer

Clarify & scope

I’d first ask what business outcome matters most—growth, margin, retention, risk reduction, or customer experience—and what decision the business needs to make. “Use more data science” is not a goal. The opportunity is to improve a recurring decision enough to create measurable value, while ensuring the result can be acted on.

Users & pain points

I’d identify the decision-makers and the people affected. For example, a sales leader may need to allocate limited rep time, while customers need relevant outreach rather than more messages. I’d choose a well-defined, high-volume decision where current performance is inconsistent, costly, or constrained by human capacity.

Goals & success metrics

I’d establish a baseline and choose a primary metric tied to business value, such as incremental gross margin, conversion, retention, or cost per successful outcome. I’d pair it with guardrails: customer complaints, fairness across groups, operational workload, latency, and model or data quality. I’d distinguish model metrics from business metrics: a better AUC is not valuable unless it improves the decision and the outcome.

Solutions

I’d consider a range of approaches, not assume that a predictive model is the answer:

  • Better measurement or dashboards, if the issue is lack of visibility.
  • A simple rule or workflow change, if the decision is straightforward.
  • A predictive or optimization system, if it improves a complex decision at scale.
  • An experiment, if the causal impact of an intervention is uncertain.

Recommendation: Start with the smallest intervention that can test the value hypothesis. For a sales prioritization use case, compare current practice with a ranked list in a randomized pilot. Keep a human in control initially, and measure incremental outcomes—not just model accuracy.

Prioritization & trade-offs

I’d rank opportunities by expected value, confidence, implementation effort, time to learn, and downside risk. I’d account for data readiness and workflow adoption: a slightly less accurate solution that teams use can outperform a sophisticated system that is ignored. I’d also consider opportunity cost and whether the work creates reusable data or platform capabilities.

MVP, measurement & rollout

I’d agree on an owner, baseline, experiment design, decision threshold, and rollback criteria before launch. Run a limited pilot with a holdout where feasible, monitor guardrails, and review results with business partners. Scale only when the lift is credible, operationally sustainable, and worth the cost. As a manager, I’d align teams on the decision and value case, develop the right mix of analytical and engineering skills, and ensure ongoing ownership after launch.

Product & growthEasyMetaData Science ManagerBusiness/Product Sense

10. How can data improve a company’s operations?

Model answer

Clarify & scope

I’d clarify which operation is in scope—such as inventory planning, customer support, workforce scheduling, or fulfillment—and what is currently costly or unreliable. I’d ask who makes the decision, how often it is made, what constraints exist, and whether the goal is lower cost, faster service, fewer errors, or greater capacity. I would treat data as a way to improve a decision or process, not as an end in itself.

Users & pain points

I’d focus on the frontline operator and their manager. For example, a support operations lead may have to schedule shifts using historical averages, while demand varies by hour and issue type. That can create long customer wait times during peaks and underused capacity during quiet periods. I’d validate the workflow with the people doing the work before designing an analytical solution.

Goals & success metrics

I’d define a primary operational outcome and its baseline. For support staffing, that could be the share of customers receiving a response within the service target, subject to a labor-cost ceiling. Guardrails might include backlog, customer satisfaction, employee schedule stability, overtime, and performance across customer segments. I’d track adoption and forecast error as diagnostic measures, but not mistake either for business impact.

Solutions

I’d consider options in order of complexity:

  • Improve instrumentation and dashboards so teams can identify bottlenecks.
  • Use forecasting to anticipate demand, then help managers plan capacity.
  • Add optimization or decision support to recommend schedules under labor, skills, and service constraints.
  • Redesign the underlying process if the main problem is handoffs, policy, or incentives rather than prediction.

Recommendation: For variable support demand, begin with a demand forecast and a planning tool that presents recommendations and uncertainty to managers. Keep human approval during the pilot; do not automate schedules before confirming that the recommendations are accurate, fair, and usable.

Prioritization & trade-offs

I’d prioritize by operational value, data readiness, implementation cost, and time to learn. Forecast accuracy may improve with more granular data, but that can increase complexity and privacy risk. A model that is marginally more accurate may not be worth deploying if it makes schedules unstable or difficult to explain. I’d also account for integration with existing planning tools and the cost of maintaining the system.

MVP, measurement & rollout

I’d pilot in a bounded operation, compare outcomes with a credible baseline or control, and establish rollback conditions in advance. Review service, cost, quality, and workforce guardrails with operators regularly. If results are positive and sustained, expand by region or team while monitoring for drift. As a Data Science Manager, I’d bring Operations, Product, Engineering, and frontline teams into the design, assign clear ownership, and ensure recommendations fit the actual decision workflow.

Product & growthEasyMetaProduct Manager

11. What is your favorite product and why?

Model answer

Clarify: Choose a product that you use frequently and have a deep understanding of. It could be a tech product or something from everyday life.

User segments & pain points: Identify who the product serves and what problems it solves. Explain why these aspects are important to you.

Goals & success metrics: Discuss the product's main goals and how it measures success. This could include user satisfaction, market share, or innovation.

Features & impact: Highlight key features that make the product stand out and how they impact your life or work positively.

Recommendation: Conclude with why you would recommend this product to others, emphasizing its unique value proposition and personal significance.

Product & growthMediumMetaData Science ManagerProduct Leadership/Product Sense

12. What criteria do you use to select KPIs for a product or team, what information do you need, and who should you work with?

Model answer

Clarify & scope

I start by asking what decision the KPI should inform and what product or team outcome we are trying to change. I clarify the audience, time horizon, product stage, and whether we are measuring health, growth, quality, or execution. A KPI is useful only if someone can act on it.

User segments & pain points

I identify the users and stakeholders affected by the outcome, then check whether one aggregate measure would hide important differences. For example, activation may look healthy overall while failing for a key customer segment or platform.

Goals & success metrics

I select a small set of measures with complementary roles:

  • North Star or outcome KPI: captures durable customer or business value, not just activity.
  • Leading indicators: help teams understand whether progress is likely before the outcome changes.
  • Guardrails: protect quality, trust, cost, and user experience while optimizing the primary KPI.

I evaluate candidates for strategic alignment, clear definitions, data quality, timeliness, sensitivity to product changes, and whether the team can influence them. I also test for gaming risk and unintended incentives. For example, optimizing time spent may increase engagement while making a task harder to complete, so I would pair it with task success or user satisfaction.

Solutions

Before committing, I need the product strategy, user research, business model, baseline and trend, event coverage, segment definitions, experiment history, and known data limitations. I work with the product manager to connect the KPI to strategy and decisions; engineering and analytics engineering to validate instrumentation; researchers and designers to understand user value; and finance, operations, or marketing where their outcomes are implicated. I agree on the metric owner, source of truth, refresh cadence, and decision thresholds.

Prioritization & trade-offs

I favor a small, stable KPI set over a dashboard of loosely related metrics. When a measure is noisy or slow-moving, I retain it as an outcome metric and use validated leading indicators for faster iteration rather than pretending the proxy is the outcome.

MVP, measurement & rollout

I document the definition, exclusions, denominator, and segments; back-test it against historical decisions; then publish a baseline and review cadence. I revisit the KPI when strategy, user behavior, or the product changes. I watch for definition drift and guardrail deterioration, and change the measure through an explicit review rather than silently redefining success.

System designEasyMetaData ScientistTechnical Screen

13. You are a Data Scientist working on content integrity / harmful content at a large social media platform (e.g., hate/harassment, self-harm, graphic…

The full question

You are a Data Scientist working on content integrity / harmful content at a large social media platform (e.g., hate/harassment, self-harm, graphic violence, sexual exploitation, spam, misinformation). Not all harmful content is equally severe. The team wants to reduce the harm users experience and is proposing an intervention — for example a new ranking demotion, a removal/enforcement policy change, or a new ML classifier + enforcement workflow.

Design a measurement and experimentation framework for this problem. Address the following:

  1. Define "severity" of harmful content.
  • Propose a severity framework that supports both measurement and decision-making.
  • What signals would you use (policy labels, human review, user reports, downstream user harm, virality, repeat exposure, content type, viewer vulnerability)?
  • Would you represent severity as a binary label, ordinal levels, or a continuous score — and why? Discuss the pros/cons of each.
  • Explain tradeoffs (interpretability vs. sensitivity, policy alignment, subjectivity, multilingual / cross-region considerations).
  1. Design metrics (primary / diagnostic / guardrails).
  • Give a clearly defined primary metric capturing harmful-content impact, several diagnostic metrics that explain movement, and several guardrail metrics that detect unintended harm.
  • Distinguish between prevalence (creation-side), exposure (distribution-side), severity-weighted exposure, enforcement accuracy, and user-experience side effects. State the pros/cons of each.
  • Specify exact definitions (numerators/denominators) and any weighting (e.g., by exposure or severity).
  • What denominator is appropriate — content created, content viewed/impressions, active users, or sessions — and how does it depend on the intervention?
  1. Design an experiment to evaluate the intervention.
  • Choose an appropriate randomization unit (viewer/user, viewer-session, content item, author/creator, community/network cluster, or geo) and justify it. Discuss the tradeoffs of each.
  • Specify the primary success metric, guardrail metrics, and long-term metrics.
  • Discuss pitfalls: interference / spillover (content spreads across users and social graphs), network effects, contamination, novelty effects, delayed outcomes, and measurement error. How would you handle interference?
  • Explain the analysis plan (intent-to-treat vs. per-protocol, variance reduction, segmentation, multiple testing).
  1. Biases, pitfalls, and edge cases.
  • Identify sources of selection bias (reporting bias / brigading), labeling bias and reviewer drift, delayed feedback, and Simpson's paradox / subgroup regressions.
  • How would you handle rare-but-severe harms versus common low-severity harms (the base-rate problem)?
  • How would you prevent the team from "improving" the chosen metric while making the platform worse overall (metric gaming)?
  • How would you make the final launch recommendation?

Assumptions

  • You can log impressions/views, engagement, reports, enforcement actions, and model outputs.
  • "Harmful content" is determined by a combination of policy rules, human review, and ML signals (imperfect).

Model answer

1. Define "severity" of harmful content

  • Severity Framework:
  • Levels of Severity:
  • Low: Minor insults, spam.
  • Medium: Harassment, misinformation.
  • High: Self-harm, graphic violence, sexual exploitation.
  • Signals to Use:
  • Policy labels (predefined categories).
  • Human review outcomes (expert assessments).
  • User reports (direct feedback).
  • Downstream user harm (impact on user well-being).
  • Virality (spread of content).
  • Repeat exposure (frequency of harmful content).
  • Content type (text, image, video).
  • Viewer vulnerability (demographic factors).
  • Representation of Severity:
  • Binary Label:
  • Pros: Simple, easy to implement.
  • Cons: Oversimplifies nuances, lacks granularity.
  • Ordinal Levels:
  • Pros: Captures varying degrees of severity, interpretable.
  • Cons: Subjective, may require calibration.
  • Continuous Score:
  • Pros: Highly sensitive, captures subtle differences.
  • Cons: Complex to interpret, may introduce noise.
  • Trade-offs:
  • Interpretability vs. sensitivity: Continuous scores may be less interpretable.
  • Policy alignment: Must align with existing guidelines.
  • Subjectivity: Human reviews can introduce bias.
  • Multilingual/cross-region considerations: Cultural differences in interpreting severity.

2. Design metrics (primary / diagnostic / guardrails)

  • Primary Metric:
  • Severity-Weighted Exposure:
  • Numerator: Total views of harmful content weighted by severity level.
  • Denominator: Total content views.
  • Diagnostic Metrics:
  • Prevalence:
  • Numerator: Count of harmful content created.
  • Denominator: Total content created.
  • Enforcement Accuracy:
  • Numerator: Correctly identified harmful content.
  • Denominator: Total identified harmful content.
  • Guardrail Metrics:
  • User-Experience Side Effects:
  • Measure user engagement metrics (e.g., session duration, user retention).
  • Content Type Distribution:
  • Monitor shifts in content types post-intervention.
  • Denominator Considerations:
  • Content Created: Useful for prevalence metrics.
  • Content Viewed/Impressions: Relevant for exposure metrics.
  • Active Users/Sessions: Important for user experience metrics.

3. Design an experiment to evaluate the intervention

  • Randomization Unit:
  • Content Item:
  • Justification: Allows for direct measurement of content impact on users.
  • Trade-offs: May overlook user-level effects; however, it isolates content variability.
  • Primary Success Metric:
  • Reduction in severity-weighted exposure.
  • Guardrail Metrics:
  • User engagement metrics (e.g., session duration).
  • Enforcement accuracy.
  • Long-term Metrics:
  • User reports of harmful content.
  • Changes in user sentiment.
  • Pitfalls:
  • Interference/Spillover: Use clustering to minimize cross-contamination.
  • Network Effects: Monitor community-level changes.
  • Delayed Outcomes: Implement follow-up assessments.
  • Measurement Error: Use robust data collection methods.
  • Analysis Plan:
  • Intent-to-treat analysis to account for all randomized units.
  • Variance reduction techniques (e.g., stratification).
  • Multiple testing corrections to avoid false positives.

4. Biases, pitfalls, and edge cases

  • Selection Bias:
  • Reporting bias from users may skew data.
  • Labeling bias from reviewers can affect severity assessments.
  • Handling Rare vs. Common Harms:
  • Develop separate strategies for high-impact, low-frequency events.
  • Ensure that common low-severity harms do not overshadow critical issues.
  • Preventing Metric Gaming:
  • Establish a balanced scorecard approach to capture multiple dimensions of success.
  • Regular audits of metrics and outcomes.
  • Final Launch Recommendation:
  • Based on comprehensive analysis of metrics and user feedback.
  • Emphasize alignment with overall platform goals and user safety.
System designEasyMeta

14. Design a simple news feed system for a social media platform.

Model answer

1. Requirements & scale

Functional Requirements:

  • Users can view a personalized news feed.
  • Users can post new content.
  • Users can like and comment on posts.
  • The system should deliver real-time updates.

Non-Functional Requirements:

  • Low latency for feed updates.
  • High availability and reliability.
  • Scalability to handle millions of users.
  • Consistency in displaying the latest posts.

Estimates:

  • Assume 100 million daily active users, with each user making 5 requests per day on average.
  • Total requests per day = 500 million.
  • QPS (Queries Per Second) = 500 million / 86,400 seconds ≈ 5,800 QPS.
  • Average post size = 1 KB. If each user views 100 posts per day, data transfer = 100 million 100 1 KB = 10 TB/day.
  • Storage: Assume 1 billion posts with an average size of 1 KB = 1 TB of storage.

2. High-level architecture

flowchart TD
    subgraph Client
        A[Mobile App]
        B[Web App]
    end

    subgraph Edge/CDN
        C[CDN]
    end

    subgraph Load Balancer
        D[Load Balancer]
    end

    subgraph API / Services
        E[Feed Service]
        F[Post Service]
        G[User Service]
    end

    subgraph Cache
        H[Redis Cache]
    end

    subgraph Datastores
        I["SQL DB (User, Post)"]
        J["NoSQL DB (Feed)"]
    end

    subgraph Message Queue
        K[Kafka]
    end

    subgraph Workers
        L[Feed Generator]
    end

    A --> C
    B --> C
    C --> D
    D --> E
    D --> F
    D --> G
    E --> H
    H --> I
    F --> I
    G --> I
    F --> K
    K --> L
    L --> J
    E --> J
Diagram

3. API design

  • GET /feed: Retrieve the user's news feed.
  • POST /post: Create a new post.
  • POST /like: Like a post.
  • POST /comment: Comment on a post.
  • GET /user/{id}: Retrieve user profile information.

4. Data model & storage

Datastores:

  • SQL Database:
  • User Table: Stores user information.
  • Post Table: Stores post metadata and content.
  • NoSQL Database:
  • Feed Collection: Stores precomputed feeds for fast retrieval.
  • Cache:
  • Redis: Caches frequently accessed feeds and user data to reduce load on databases.

Partitioning Strategy:

  • User Table: Partition by user ID.
  • Post Table: Partition by post ID.
  • Feed Collection: Partition by user ID to ensure fast access to a user's feed.

5. Deep dive

The core challenge is efficiently generating and updating the news feed. We use a fan-out-on-write approach:

sequenceDiagram
    participant User as User
    participant PostService as Post Service
    participant Kafka as Kafka
    participant FeedGen as Feed Generator
    participant NoSQL as NoSQL DB

    User->>PostService: Create Post
    PostService->>Kafka: Publish Post Event
    Kafka->>FeedGen: Consume Post Event
    FeedGen->>NoSQL: Update Feeds
Diagram
  1. Post Creation: When a user creates a post, the Post Service stores it in the SQL database and publishes an event to Kafka.
  2. Feed Generation: The Feed Generator consumes the event and updates the relevant users' feeds in the NoSQL database.
  3. Feed Retrieval: When a user requests their feed, the Feed Service retrieves it from the NoSQL database, using Redis for caching to improve performance.

6. Scale, bottlenecks & trade-offs

Scalability:

  • Sharding: Both SQL and NoSQL databases are sharded by user ID to distribute load evenly.
  • Caching: Redis is used to cache frequently accessed data, reducing database load.

Bottlenecks:

  • Feed Generation: The fan-out-on-write approach can be resource-intensive. Scaling the Feed Generator horizontally can mitigate this.
  • Real-time Updates: Ensuring low latency for real-time updates can be challenging. Using WebSockets or long polling can help.

Trade-offs:

  • Consistency vs. Availability: Opt for eventual consistency in feed updates to ensure high availability.
  • Push vs. Pull: Use a combination of push notifications for critical updates and pull for regular feed refreshes.
  • SQL vs. NoSQL: SQL is used for structured data with relationships, while NoSQL is used for high-throughput feed storage.
System designEasyMetaSoftware EngineerOnsite

15. Design a scalable online auction service.

The full question

Design a scalable online auction service.

Users can:

  • Create an auction (item info, start/end time, reserve price optional).
  • Place bids while the auction is live.
  • See the current winning bid and bid history.
  • Receive near-real-time notifications when the winning bid changes and when the auction ends.

Design goals and constraints:

  • Many auctions run concurrently; bids can spike near the end.
  • Correctness: determine the winner unambiguously; prevent accepting bids after the end time.
  • Low latency for bid placement and for notifying watchers.
  • The system should scale horizontally.

What APIs, data model, storage, messaging/pub-sub, and real-time push mechanism would you use? Include a rough QPS/throughput estimation approach and how you would partition/shard data (e.g., by auctionId).

Model answer

1. Requirements & scale

Functional Requirements:

  • Users can create auctions with item details, start/end times, and optional reserve prices.
  • Users can place bids while auctions are live.
  • Users can view the current winning bid and bid history.
  • Users receive near-real-time notifications for bid changes and auction endings.

Non-Functional Requirements:

  • High availability and low latency for bid placements and notifications.
  • Scalability to handle many concurrent auctions and bid spikes near auction end times.
  • Consistency to ensure no bids are accepted after auction end times.

Estimates:

  • Assume 1 million active users, with 10% participating in auctions at any time.
  • Average of 100 bids per auction, with peak activity at auction end.
  • If each user places 1 bid per minute during peak, estimate 100,000 bids per minute (1,667 QPS).
  • Storage: Assume each auction stores 1 KB of metadata and 1 KB per bid. For 1 million auctions with 100 bids each, storage is approximately 200 GB.

2. High-level architecture

flowchart TD
    subgraph Client
        A[User Interface]
    end

    subgraph "Edge/CDN"
        B[Edge Servers]
    end

    subgraph "Load Balancer"
        C[Load Balancer]
    end

    subgraph "API / Services"
        D[Auction Service]
        E[Bid Service]
        F[Notification Service]
    end

    subgraph "Cache"
        G[Redis Cache]
    end

    subgraph "Datastores"
        H["SQL DB (Auctions)"]
        I["NoSQL DB (Bids)"]
    end

    subgraph "Message Queue"
        J[Kafka]
    end

    subgraph Workers
        K[Notification Workers]
    end

    A --> B --> C --> D
    A --> B --> C --> E
    D --> H
    E --> I
    E --> G
    E --> J
    J --> K
    K --> F
    F --> A
Diagram

3. API design

  • POST /auctions: Create a new auction.
  • GET /auctions/{auctionId}: Retrieve auction details and current winning bid.
  • POST /auctions/{auctionId}/bids: Place a bid on an auction.
  • GET /auctions/{auctionId}/bids: Retrieve bid history for an auction.
  • GET /notifications: Fetch notifications for bid changes and auction endings.

4. Data model & storage

Datastores:

  • SQL Database (Auctions): Store auction metadata for ACID properties.
  • Table: Auctions
  • Columns: auctionId (PK), itemInfo, startTime, endTime, reservePrice
  • NoSQL Database (Bids): Store bids for scalability and high write throughput.
  • Table: Bids
  • Columns: bidId (PK), auctionId (Partition Key), userId, amount, timestamp

Cache:

  • Redis: Cache current winning bid and recent bid history for quick access.

5. Deep dive

The core challenge is handling bid spikes and ensuring real-time notifications. We use a combination of caching, message queues, and WebSockets for real-time updates.

sequenceDiagram
    participant U as User
    participant UI as User Interface
    participant S as Bid Service
    participant C as Redis Cache
    participant MQ as Kafka
    participant NW as Notification Worker
    participant NS as Notification Service

    U->>UI: Place Bid
    UI->>S: POST /auctions/{auctionId}/bids
    S->>C: Check Cache for Current Winning Bid
    alt Bid is Higher
        S->>C: Update Cache with New Winning Bid
        S->>MQ: Publish Bid Event
    end
    MQ->>NW: Consume Bid Event
    NW->>NS: Send Real-Time Notification
    NS->>UI: Push Notification
Diagram

6. Scale, bottlenecks & trade-offs

Scaling:

  • Horizontal Scaling: Use microservices architecture to scale individual components independently.
  • Sharding: Partition bids by auctionId to distribute load across multiple NoSQL nodes.

Bottlenecks:

  • Bid Spikes: Use Redis to cache winning bids and recent bid history to reduce database load.
  • Notification Delays: Use Kafka for reliable message delivery and WebSockets for real-time notifications.

Trade-offs:

  • Consistency vs. Availability: Prioritize consistency to ensure no bids are accepted post-auction end.
  • Push vs. Pull Notifications: Use WebSockets for push notifications to minimize latency.
  • SQL vs. NoSQL: Use SQL for auction metadata to ensure ACID properties, and NoSQL for bids to handle high write throughput.
System designEasyMetaData ScientistOnsite

16. You work on a social platform.

The full question

You work on a social platform. The only product surface you can rely on is friend requests (sending/receiving/accepting/declining). Assume you have no existing anti-fake model, no rules, and no established metrics.

Task

  1. Define “fake account” operationally.
  • What behaviors qualify (spam, scam, bot, account farming)?
  • How will you handle ambiguous/gray accounts?
  1. Design the data and instrumentation.
  • What events and fields would you log for friend requests and subsequent user actions?
  • What joins/identifiers are needed to track outcomes over time?
  1. Propose an initial detection approach without a model.
  • What heuristic signals or risk scoring would you start with (rate limits, graph patterns, acceptance ratios, burstiness, messaging-after-accept if available, etc.)?
  • How would you choose thresholds and prevent hurting legitimate users?
  1. Measurement & evaluation plan.
  • How will you obtain labels (manual review, user reports, enforcement actions) and deal with delayed/biased labels?
  • What are the primary, diagnostic, and guardrail metrics?
  1. Platform-level reporting.
  • How would you estimate and report the platform’s fake-account problem over time (prevalence/incidence), given that you only observe partial ground truth?
  • What would you show to an executive audience vs an operational team?

Model answer

1. Requirements & scale

Functional Requirements:

  • Detect and classify fake accounts based on friend request behaviors.
  • Handle ambiguous or gray accounts with a review mechanism.
  • Log and track user actions related to friend requests.

Non-Functional Requirements:

  • Minimize false positives to avoid impacting legitimate users.
  • Ensure scalability to handle millions of users and requests.
  • Provide timely detection and reporting.

Scale Estimates:

  • Assume 1 billion users with an average of 10 friend requests per user per month.
  • Total friend requests per month = 10 billion.
  • Average QPS (Queries Per Second) for friend requests = 3,800.
  • Storage for logging: 100 bytes per request, leading to approximately 1 TB per month.

2. High-level architecture

flowchart TD
    subgraph Client
        A[User Device]
    end

    subgraph Edge/CDN
        B[CDN]
    end

    subgraph Load Balancer
        C[Load Balancer]
    end

    subgraph API / Services
        D[Friend Request Service]
        E[User Action Logger]
    end

    subgraph Cache
        F[Redis Cache]
    end

    subgraph Datastores
        G[SQL Database]
        H[NoSQL Database]
    end

    subgraph Message Queue
        I[Kafka Queue]
    end

    subgraph Workers
        J[Heuristic Analysis Worker]
    end

    A -->|Send/Receive Friend Request| B
    B --> C
    C --> D
    D -->|Log Request| E
    E -->|Store Logs| H
    D -->|Check Cache| F
    F -->|Fetch Data| G
    D -->|Publish Event| I
    I --> J
    J -->|Analyze & Flag| G
Diagram

3. API design

  • POST /friend-request/send: Send a friend request to another user.
  • POST /friend-request/accept: Accept a received friend request.
  • POST /friend-request/decline: Decline a received friend request.
  • GET /friend-request/status: Retrieve the status of a sent or received friend request.

4. Data model & storage

Datastores:

  • SQL Database: For structured data like user profiles and friend connections.
  • NoSQL Database: For logging events and actions due to its scalability and flexibility.

Key Tables:

  • FriendRequests: request_id, sender_id, receiver_id, status, timestamp.
  • UserActions: action_id, user_id, action_type, timestamp.

Partition Key:

  • Use user_id for partitioning to ensure even distribution and efficient querying.

5. Deep dive

The core of detecting fake accounts involves analyzing friend request patterns and user behaviors. The heuristic approach includes:

  • Rate Limits: Monitor the number of friend requests sent per user per hour/day.
  • Graph Patterns: Identify unusual patterns like a high number of requests with low acceptance.
  • Acceptance Ratios: Calculate the ratio of accepted to sent requests.
  • Burstiness: Detect sudden spikes in friend request activity.
  • Post-Acceptance Messaging: If available, track messaging activity after acceptance to identify spam.
sequenceDiagram
    participant U as User
    participant S as Friend Request Service
    participant L as Logger
    participant W as Worker
    participant D as Database

    U->>S: Send Friend Request
    S->>L: Log Request
    S->>D: Store Request
    S->>W: Publish Event
    W->>D: Fetch User Data
    W->>W: Analyze Patterns
    W->>D: Flag Suspicious Accounts
Diagram

6. Scale, bottlenecks & trade-offs

Scalability: Use horizontal scaling for the Friend Request Service and the Logger to handle high QPS. Employ sharding in the NoSQL database to manage large volumes of log data.

Bottlenecks: The main bottleneck is the analysis worker, which must process large volumes of data quickly. Use distributed processing frameworks to scale.

Trade-offs:

  • Consistency vs. Availability: Prioritize availability for user actions, but ensure eventual consistency for analysis results.
  • False Positives vs. False Negatives: Balance between catching fake accounts and minimizing impact on legitimate users by adjusting heuristic thresholds.
  • Push vs. Pull: Use a push model for real-time detection and a pull model for batch analysis.

By implementing these strategies, the system can effectively identify and manage fake accounts while minimizing disruption to legitimate users.

TechnicalEasyMetaEngineering Manager

17. What are your current responsibilities?

Model answer

I’d answer with the scope I actually own, then connect day-to-day work to team and business outcomes. For example:

  1. Set direction and priorities. I work with product, design, and partner teams to turn company goals into a roadmap for [team or domain]. I make trade-offs explicit when reliability, delivery speed, and feature work compete, and I communicate what we are not doing as well as what we are doing.
  2. Build and develop the team. I’m responsible for hiring, onboarding, coaching, performance feedback, and succession planning for [team size and roles]. I aim to give engineers clear ownership and growth opportunities, while addressing performance issues early and fairly.
  3. Deliver healthy systems. I partner with technical leads on architecture and operational priorities without taking over their design decisions. I review delivery risks, service health, incident follow-ups, and technical-debt plans; for example, I track [specific reliability or delivery metric] alongside product outcomes.
  4. Create alignment across teams. I resolve dependencies with [partner teams], clarify decision owners, and escalate risks early. When priorities conflict, I bring the options, impact, and recommendation rather than simply forwarding the disagreement.
  5. Measure impact and improve the organization. I use a small set of metrics—such as customer outcomes, reliability, lead time, and team health—to check whether our plans are working. I adjust the roadmap or operating model based on what those measures and customer feedback show.

I’d close with one concrete example: “Recently, I [specific action], which helped the team [quantified result]. My role was to set context, align the right people, and make sure we learned from the outcome—not to be the decision-maker on every technical detail.”

What interviewers listen for

  • Clear scope: team, domain, and decision-making responsibilities.
  • A balance of people leadership, delivery, technical health, and cross-functional work.
  • Evidence of outcomes, with metrics appropriate to the candidate’s actual role.
TechnicalEasyMetaData ScientistOnsite

18. Two rooms may be occupied with the following priors: with probability 1/3 both rooms are occupied, with probability 1/3 exactly one room is occupie…

The full question

Two rooms may be occupied with the following priors: with probability 1/3 both rooms are occupied, with probability 1/3 exactly one room is occupied, and with probability 1/3 both are empty. You pick a room uniformly at random to check. (a) What is the probability the room you check is occupied? (b) Given you find your chosen room occupied, what is the probability the other room is also occupied? Show the Bayes calculation.

Model answer

Solution

To solve this problem, we need to calculate two probabilities using the given priors and Bayes' theorem.

(a) Probability the room you check is occupied
  1. Define events: - \( A \): The event that the room you check is occupied. - \( B \): The event that both rooms are occupied. - \( C \): The event that exactly one room is occupied. - \( D \): The event that both rooms are empty.
  2. Given probabilities: - \( P(B) = \frac{1}{3} \) - \( P(C) = \frac{1}{3} \) - \( P(D) = \frac{1}{3} \)
  3. Calculate \( P(A) \): - If both rooms are occupied (\( B \)), the probability of picking an occupied room is 1. - If exactly one room is occupied (\( C \)), the probability of picking an occupied room is \( \frac{1}{2} \). - If both rooms are empty (\( D \)), the probability of picking an occupied room is 0.

Therefore, using the law of total probability: \[ P(A) = P(A|B)P(B) + P(A|C)P(C) + P(A|D)P(D) = 1 \times \frac{1}{3} + \frac{1}{2} \times \frac{1}{3} + 0 \times \frac{1}{3} = \frac{1}{3} + \frac{1}{6} = \frac{1}{2} \]

(b) Probability the other room is also occupied given the room you check is occupied
  1. Define event \( E \): The event that the other room is also occupied.
  2. Use Bayes' theorem: - We need to find \( P(E|A) \).
  3. Calculate \( P(E|A) \): - \( P(E|A) = \frac{P(A|E) \cdot P(E)}{P(A)} \)
  4. Calculate components: - \( P(A|E) \): If the other room is also occupied, the probability that the room you check is occupied is 1. - \( P(E) = P(B) = \frac{1}{3} \) (since both rooms being occupied is the same as event \( B \)). - \( P(A) = \frac{1}{2} \) (from part (a)).
  5. Substitute into Bayes' theorem: \[ P(E|A) = \frac{1 \times \frac{1}{3}}{\frac{1}{2}} = \frac{2}{3} \]

Conclusion

  • (a) The probability that the room you check is occupied is \( \frac{1}{2} \).
  • (b) Given that the room you check is occupied, the probability that the other room is also occupied is \( \frac{2}{3} \).
TechnicalEasyMeta

19. What is the difference between a stack and a queue?

Model answer

Stack vs Queue

  1. Data Structure Type: - Stack: A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. - Queue: A queue is a linear data structure that follows the First In First Out (FIFO) principle. This means that the first element added to the queue will be the first one to be removed.
  2. Basic Operations: - Stack: - Push: Add an element to the top of the stack. - Pop: Remove the element from the top of the stack. - Peek/Top: View the top element of the stack without removing it. - Queue: - Enqueue: Add an element to the end of the queue. - Dequeue: Remove the element from the front of the queue. - Front: View the front element of the queue without removing it.
  3. Use Cases: - Stack: Useful in scenarios where you need to reverse items, such as undo mechanisms in text editors, parsing expressions (e.g., evaluating postfix expressions), and managing function calls (call stack). - Queue: Suitable for scenarios where order needs to be preserved, such as scheduling tasks, handling requests in a server, and breadth-first search in graphs.
  4. Memory Structure: - Stack: Typically implemented using arrays or linked lists, with a pointer to the top of the stack. - Queue: Can be implemented using arrays or linked lists, with pointers to both the front and rear of the queue.
  5. Complexity: - Stack: Both push and pop operations have a time complexity of O(1). - Queue: Both enqueue and dequeue operations have a time complexity of O(1) when implemented with a linked list or a circular array.

Understanding these differences helps in choosing the right data structure for specific problems based on the required operations and performance characteristics.

TechnicalEasyMetaPrincipal Engineer

20. What happens behind the scenes when you type ls in a shell?

Model answer

  1. The shell interprets the command. It tokenizes ls, handles quoting and expansions, then checks whether ls is an alias, function, or builtin. In a typical interactive shell it is an external executable, often with aliases such as ls --color=auto.
  2. The shell locates the executable. It searches directories in $PATH and resolves a path such as /usr/bin/ls. If it cannot find an executable, it reports an error without starting the program.
  3. The process is started. The shell typically forks a child process, sets up file descriptors and any redirections or pipelines, then uses an exec call to replace the child process with ls. The shell waits for the child unless the command is backgrounded.
  4. ls reads directory entries. On Linux, directory-reading library calls commonly result in a getdents64 system call. The kernel checks permissions and returns entries through the VFS; filesystem metadata or directory contents may already be in the page cache.
  5. Options determine extra work. Plain ls generally prints names. Options such as -l require metadata lookups (often via stat/statx) for file type, permissions, size, and timestamps. Sorting, color, locale, and terminal detection can add processing or system calls.
  6. Output returns to the terminal. ls formats and writes bytes to standard output; errors go to standard error. The terminal displays the output, and the process exits with a status code that the shell makes available as $?.
flowchart LR
  A[User types command] --> B[Shell parses and expands]
  B --> C[Resolve alias function or PATH]
  C --> D[Fork and exec ls]
  D --> E[Kernel reads directory entries]
  E --> F[ls formats output]
  F --> G[Write to stdout]
  G --> H[Shell collects exit status]
Diagram

Details vary by shell and operating system; the VFS and getdents64 examples describe a common Linux path.

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