Google (Alphabet) interview questions & answers

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

BehavioralEasyGoogle (Alphabet)Software EngineerOnsite

1. Describe a time when you faced a serious conflict at work (e.g., disagreement on technical direction, priorities, scope, or execution) involving on…

The full question

Describe a time when you faced a serious conflict at work (e.g., disagreement on technical direction, priorities, scope, or execution) involving one or more of:

  • A peer engineer
  • Your manager / leadership
  • Cross-functional stakeholders (PM, DS, SRE, Security, etc.)

What to cover

  1. Situation & context: What was the project, timeline pressure, and what was at stake?
  2. Conflict details: What exactly did each party want, and why?
  3. Your actions: How did you de-escalate, align incentives, and drive a decision?
  4. Outcome: What changed as a result (delivery, quality, relationship, business impact)?
  5. Reflection: If you faced the same situation again, what would you do better or differently?

Evaluation focus

  • Ability to mediate conflict constructively
  • Expectation management upward and outward
  • Clarity of communication and decision-making under ambiguity

Model answer

Situation

In my role as a software engineer at a tech company, I was part of a team tasked with developing a new feature for our flagship product. The project had a tight deadline due to an upcoming major product launch, and there was significant pressure to deliver high-quality work on time. The stakes were high as this feature was a key selling point for the product and critical for our competitive positioning.

Task

During the project, I encountered a serious conflict with a peer engineer and a product manager regarding the technical direction of the feature. The peer engineer advocated for a more complex solution that promised greater scalability, while the product manager prioritized a simpler approach to meet the deadline and ensure immediate functionality.

Action

  • I initiated a meeting with both parties to discuss the conflict openly. My goal was to understand their perspectives fully and find a common ground.
  • I listened actively to the peer engineer's concerns about scalability and the product manager's focus on the timeline. I acknowledged the validity of both viewpoints, which helped in de-escalating tensions.
  • To align incentives, I proposed a phased approach: we would implement the simpler solution first to meet the immediate deadline, followed by an iterative enhancement to address scalability post-launch. This compromise allowed us to meet the product manager's timeline while not dismissing the engineer's concerns.
  • I facilitated a follow-up meeting to outline the phased plan, ensuring everyone was clear on the new direction and their responsibilities. I also documented the plan and shared it with the team to maintain transparency and accountability.

Result

The phased approach was successful. We delivered the feature on time for the product launch, which was well-received by stakeholders and customers. Post-launch, we were able to enhance the feature's scalability without major disruptions. The conflict resolution not only preserved team harmony but also improved our collaborative dynamics. Reflecting on the experience, I learned the importance of balancing immediate business needs with long-term technical goals and the value of clear, empathetic communication in resolving conflicts.

Reflection

If faced with a similar situation again, I would involve a neutral third party earlier in the process to facilitate the discussion. This could provide additional perspectives and help in reaching a resolution more efficiently. Additionally, I would ensure more frequent check-ins with all stakeholders to preemptively address any emerging conflicts.

BehavioralEasyGoogle (Alphabet)Director of Engineering

2. How do you deal with criticism?

Model answer

Situation

During a quarterly planning review, a product and engineering peer told me that my team’s roadmap was technically sound but too difficult for partner teams to understand and depend on. The feedback was uncomfortable because I had invested heavily in the plan, but it pointed to a real organizational problem: teams were learning about interface changes too late.

Task

I needed to understand whether the criticism reflected an isolated communication gap or a broader weakness in how my organization planned and delivered cross-team work, then respond without becoming defensive.

Action

  • I thanked the person and asked for specific examples: where the handoff failed, what impact it had, and what they would have needed earlier. I listened without rebutting each point in the moment.
  • I separated intent from impact. My intent had been to give my team focus; the impact was that partners could not plan reliably. I checked that interpretation with other team leads and reviewed missed dependency dates and late changes.
  • I acknowledged the gap directly with my leadership team rather than treating it as an individual communication issue. We identified unclear ownership and late interface decisions as the main causes.
  • I introduced a lightweight dependency review at quarterly planning, with named owners, target decision dates, and a written change log for cross-team interfaces. I deliberately avoided adding a large approval process that would slow teams down.
  • I followed up with the original peer after the next planning cycle, asking whether the changes had made collaboration easier and what still felt cumbersome.

Result

Partner teams had earlier visibility into dependencies, and we reduced late cross-team scope changes by [insert your verified measure] over the following cycles. The feedback also changed how I lead reviews: I now ask not only whether a plan is correct, but whether the people who depend on it can act on it. I’ve learned that receiving criticism well means turning it into observable changes, not just thanking someone for saying it.

What interviewers listen for

  • You stay curious and non-defensive while testing the feedback.
  • You own your part and address systemic causes, not just symptoms.
  • You close the loop and can point to a measurable change.

Replace the example and metric with a real situation from your career.

BehavioralEasyGoogle (Alphabet)

3. Tell me about a time you had to learn a new technology quickly to complete a project.

Model answer

Situation

In my previous role as a software developer at a mid-sized tech company, I was assigned to a project that required integrating a new cloud-based service into our existing infrastructure. This was crucial because the service promised to significantly enhance our application's performance and scalability. However, I had no prior experience with this specific technology, and the timeline was tight due to an upcoming product launch.

Task

My primary responsibility was to quickly learn and implement this new technology to ensure the integration was seamless and met the performance benchmarks. The key constraint was the limited time available to both learn and apply this technology effectively.

Action

  • I began by dedicating the first few days to intensive research and learning. I utilized official documentation, online courses, and community forums to get up to speed with the technology.
  • To accelerate my learning, I reached out to a colleague who had experience with similar technologies. We scheduled a few knowledge-sharing sessions where I could ask specific questions and gain insights from their practical experience.
  • I set up a small prototype environment to experiment with the technology. This hands-on approach allowed me to test various configurations and understand the nuances of the service.
  • I broke down the integration task into smaller, manageable components and set mini-deadlines to track my progress. This helped me stay focused and ensured that I was making consistent progress.
  • Throughout the process, I maintained open communication with my team and project manager, providing regular updates on my progress and any challenges I encountered. This transparency helped manage expectations and allowed the team to plan accordingly.

Result

As a result of these efforts, I successfully integrated the new cloud-based service into our application ahead of the deadline. The integration led to a 25% improvement in application performance, which was well-received by both the team and our clients. This experience taught me the value of leveraging available resources and the importance of effective time management when learning new technologies under pressure. It reinforced my ability to adapt quickly and deliver results in challenging situations.

BehavioralEasyGoogle (Alphabet)DevOps / SRE

4. Can you tell me about a time you automated a manual process?

The full question

Can you tell me about a time you automated a manual process? What was the outcome?

Model answer

Situation In my previous role as a software engineer at a mid-sized e-commerce company, I noticed that our team was spending a significant amount of time manually generating and distributing weekly sales reports. This process involved extracting data from multiple sources, compiling it into a spreadsheet, and then emailing it to various stakeholders. The manual nature of this task not only consumed valuable time but also introduced opportunities for human error, which could affect decision-making.

Task My goal was to automate the report generation and distribution process to save time and reduce errors. The key constraint was ensuring that the automated solution could integrate seamlessly with our existing systems and deliver reports in a format that stakeholders were already accustomed to.

Action

  • I began by mapping out the entire manual process to understand each step and identify potential automation points.
  • I chose to use a combination of Python scripts and a scheduling tool like cron jobs to automate data extraction from our databases and third-party APIs.
  • I developed a script that compiled the extracted data into a formatted spreadsheet that matched the existing manual reports.
  • To automate distribution, I integrated the script with our email server, ensuring that the reports were sent out to the relevant stakeholders every Monday morning without fail.
  • I conducted a series of tests to ensure data accuracy and reliability of the automated process, involving key stakeholders to validate the report format and content.
  • Finally, I documented the entire process and trained a colleague to maintain the system, ensuring continuity in case of my absence.

Result The automation reduced the time spent on report generation from approximately 10 hours per week to virtually zero, freeing up the team to focus on more strategic tasks. Stakeholders received their reports consistently and without errors, leading to improved trust in the data. This project not only enhanced operational efficiency but also demonstrated the value of automation in our workflows. I learned the importance of thoroughly understanding existing processes before implementing automation, ensuring that solutions are both effective and sustainable.

CodingEasyGoogle (Alphabet)Software Engineer

5. 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.
CodingEasyGoogle (Alphabet)Software Engineer

6. 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.
CodingEasyGoogle (Alphabet)Software Engineer

7. 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.
CodingEasyGoogle (Alphabet)Software Engineer

8. Day of the Week (LeetCode)

Model answer

The task

Given a valid Gregorian calendar date, return its weekday name, such as "Monday" or "Friday".

Key idea

Count the number of days between the given date and a known date: January 1, 1971, which was a Friday. Gregorian leap-year rules let us count the intervening days in constant time, then use modulo 7 to find the weekday.

Approach

  1. Count all days in the complete years from 1971 up to, but not including, the given year.
  2. Count leap years in that range using the Gregorian rule: divisible by 4, except centuries unless divisible by 400.
  3. Add the days in the completed months of the given year, accounting for February in a leap year.
  4. Add the days elapsed in the given month.
  5. Offset from Friday by the total number of days modulo 7.
class Solution:
    def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
        weekdays = [
            "Monday", "Tuesday", "Wednesday", "Thursday",
            "Friday", "Saturday", "Sunday"
        ]
        days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

        def leap_year_count_through(y: int) -> int:
            return y // 4 - y // 100 + y // 400

        # Count days in complete years since 1971.
        previous_year = year - 1
        complete_years = year - 1971
        leap_years = (
            leap_year_count_through(previous_year)
            - leap_year_count_through(1970)
        )
        elapsed_days = 365 * complete_years + leap_years

        # Add days in complete months of the current year.
        if self._is_leap_year(year):
            days_in_month[1] = 29
        elapsed_days += sum(days_in_month[:month - 1])

        # Add days elapsed in the current month.
        elapsed_days += day - 1

        # January 1, 1971 was Friday, weekday index 4.
        return weekdays[(4 + elapsed_days) % 7]

    def _is_leap_year(self, year: int) -> bool:
        return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

Complexity:

  • Time: O(1), since the month list has a fixed size.
  • Space: O(1), using a fixed-size month list and weekday list.

Common follow-ups

  • How would you handle dates before the reference date? Use a signed day difference and normalize with modulo 7.
  • How do you validate an input date? Check the month range and compare the day with that month’s length, including leap-year February.
  • How would you support another calendar system? Replace the month-length and leap-year rules with that calendar’s rules.
Product & growthEasyGoogle (Alphabet)Product Manager

9. What is your favorite Google product and why?

Model answer

Favorite product: Google Search.

Why: Google Search is intuitive, fast, and constantly evolving to meet user needs. It's the backbone of information retrieval and has revolutionized the way people access knowledge.

Features:

  • Relevance: Advanced algorithms ensure relevant results.
  • Speed: Quick response times enhance user experience.
  • Integration: Seamless integration with other Google services.

Impact: Google Search democratizes access to information, supports businesses through SEO, and continually innovates with AI-driven features like voice search and personalized results.

Recommendation: Continue evolving AI capabilities to maintain leadership in search technology.

Product & growthMediumGoogle (Alphabet)Data Scientist

10. Say you have two countries of interest and want to compare variances of clicking behavior from users (i.e.

The full question

Say you have two countries of interest and want to compare variances of clicking behavior from users (i.e. total distribution of clicks). How would you do this comparison, and what assumptions need to be met?

Model answer

Clarify & scope

I would first define “clicking behavior” as clicks per eligible user over the same fixed window, such as seven days. Comparing raw country totals would mostly measure population size, not user behavior. I would also agree whether the goal is to compare user-level counts or click rates; if exposure opportunities differ, I would use clicks per eligible impression or model exposure explicitly.

User segments & pain points

My primary unit would be a user, with one comparable observation per user. I would check whether country differences in device, acquisition channel, or tenure are driving the apparent variance difference, and report both the overall comparison and relevant stratified comparisons.

Goals & success metrics

The primary metric is the variance of per-user clicks in each country, with the difference or ratio of variances and a confidence interval. Guardrails include sample size, missingness, exposure, and the mean click rate: a variance comparison alone can hide very different average behavior.

Solutions

  1. If users are independent and click counts are approximately normal, use a two-sample variance test such as the F-test.
  2. Since click counts are often skewed, zero-heavy, and outlier-prone, I would prefer a bootstrap confidence interval or a robust spread comparison such as Levene’s test, centered on the median (Brown–Forsythe).
  3. If exposure or user mix differs materially, compare within matched or standardized segments, or fit a count model with exposure as an offset and country-specific dispersion.

Recommendation: Use the same observation window and eligibility rules, then estimate the variance difference with a user-level bootstrap, resampling users independently within each country. Report the interval and a robust test as a sensitivity check.

Prioritization & trade-offs

The bootstrap is practical and makes fewer distributional assumptions than the F-test, but it still relies on representative, independent users. If users are clustered by household or another shared unit, resample clusters instead. If many users have different exposure, raw count variance answers a different question from variance in click propensity; I would make that distinction explicit.

MVP, measurement & rollout

Start with a fixed-window analysis, validate logging and eligibility, and publish sample sizes, means, variances, confidence intervals, and segment checks. Before interpreting a difference as behavioral, verify independence across users, comparable measurement, and adequate coverage in both countries.

Product & growthMediumGoogle (Alphabet)Product Manager

11. You're the new product manager for YouTube and you notice a drop in video engagement by 15% over the past two weeks.

The full question

You're the new product manager for YouTube and you notice a drop in video engagement by 15% over the past two weeks. What do you do?

Make it harder? The drop in engagement is globally distributed.

Model answer

Clarify & scope

First, I’d confirm what “engagement” means: watch time per viewer, minutes watched, sessions, or an aggregate metric. I’d check whether the 15% decline is relative or absolute, how it is calculated, and whether it is statistically significant. Since it is globally distributed, I would not assume a single country-specific cause—but I would still segment the data to find where the decline is largest.

Define metrics

My primary metric would be watch time per active viewer, with supporting measures such as videos watched per session, average view duration, and meaningful interactions. Guardrails would include crashes, playback start failures, latency, ad load, satisfaction signals, and policy or safety incidents. I’d compare against the same days of the week and account for seasonality.

Break down the decline

I’d first validate instrumentation and then decompose the metric by device, app and web version, traffic source, new versus returning viewers, content type, and major product surfaces such as Home, Search, and Shorts. I’d compare the funnel—impression, click, playback start, and continued viewing—to identify whether fewer people are starting videos or sessions are becoming shorter.

Investigate hypotheses

I’d investigate in this order:

  1. Measurement or data pipeline issue: a logging change, delayed events, or a dashboard definition change can create an apparent global drop.
  2. Shared technical regression: a release, experiment, CDN or playback issue, or recommendation-serving problem could affect many markets at once.
  3. Shared product or content change: ranking, notifications, ad load, or a change in content availability could reduce viewing across regions.
  4. External shift: holidays, major events, or changes in user behavior may explain the timing, but I’d require evidence before attributing causality.

I’d align the drop’s start time with launches, experiments, and infrastructure changes, then compare exposed and unexposed cohorts. I’d also use logs and playback quality data to distinguish reduced intent from failed playback.

Decision & guardrails

If a recent change is strongly associated with the decline, I’d pause or roll back the affected launch, ideally through the existing experiment or feature-flag controls, while monitoring the primary metric and guardrails. If no single cause is clear, I’d avoid a broad global rollback and run targeted diagnostics or holdouts. I’d communicate the impact, confidence, owner, and next update to engineering, analytics, and leadership, then follow through with a root-cause review and prevention actions.

Product & growthMediumGoogle (Alphabet)Product Manager

12. If you were the product manager on Calendars, how would you measure it's success?

The full question

If you were the product manager on Calendars, how would you measure it's success?

Make it harder? Evaluate at least three different user behaviors.

Model answer

Clarify & scope

I’d define success as Calendars helping people coordinate and follow through on plans—not simply increasing the number of calendars created. I’d clarify which surfaces and user groups are in scope, then evaluate both individual use and collaboration, since a calendar can be useful to one person or to a whole group.

User segments & pain points

I’d start with people who coordinate recurring events with others: they need to find a time, get invitees to respond, and keep everyone informed when plans change. I’d also separately examine solo users and occasional event creators; strong retention from power users can mask a poor experience for new users.

Goals & success metrics

My North Star would be weekly successful coordination: the number of active users who create or meaningfully update an event that another person accepts or attends. I’d pair it with three behaviors:

  1. Create: users make personal or shared events, including recurring ones.
  2. Coordinate: invitees view, accept, decline, or propose a change.
  3. Return and rely: users revisit events, respond to reminders, and make timely updates.

I’d measure conversion between these steps, time from invitation to response, and the share of new users who reach a useful first event. I’d break results down by new versus returning users, solo versus shared calendars, device, and acquisition source.

Guardrails would include notification opt-outs, duplicate or abandoned events, invite spam reports, crash and latency rates, and privacy-related complaints. A rise in event creation is not a win if it comes with more unwanted invitations or notification fatigue.

Solutions

I’d consider simplifying event creation, making invitee availability and responses easier to understand, and improving reminders or change notifications. Recommendation: prioritize the biggest measured funnel drop. For example, if events are created but invitees don’t respond, improve the invitation and response flow before adding more creation features.

Prioritization & trade-offs

I’d rank opportunities by user impact, confidence, and implementation effort. Better coordination may matter more than raw engagement, but features that expose availability need careful privacy defaults and clear user control.

MVP, measurement & rollout

I’d launch one focused improvement to a randomized cohort, define the primary metric and guardrails in advance, and compare behavior over several weeks to cover recurring use. I’d check short-term funnel changes and longer-term retention, then expand gradually if coordination improves without harming trust or reliability.

System designEasyGoogle (Alphabet)DevOps / SRE

13. Sketch a design for a simple notification system.

Model answer

1. Requirements & scale

Functional Requirements:

  • The system should send notifications to users.
  • Support multiple notification channels (e.g., email, SMS, push notifications).
  • Allow scheduling of notifications.
  • Provide a retry mechanism for failed notifications.

Non-Functional Requirements:

  • High availability and reliability.
  • Scalability to handle a large number of notifications.
  • Low latency in delivering notifications.

Estimates:

  • Assume 1 million users with an average of 5 notifications per user per day.
  • Peak load: 5 million notifications/day, approximately 58 notifications/second.
  • Storage: Minimal, primarily for logs and retry queues.
  • Bandwidth: Depends on notification size and frequency.

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["Notification API"]
        E["Scheduler Service"]
    end

    subgraph Cache
        F["In-memory Cache (Redis)"]
    end

    subgraph Datastores
        G["Metadata DB (SQL)"]
        H["Logs DB (NoSQL)"]
    end

    subgraph Message Queue
        I["Message Queue (Pub/Sub)"]
    end

    subgraph Workers
        J["Notification Workers"]
    end

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

3. API design

  • POST /notifications: Create a new notification request.
  • GET /notifications/{id}: Retrieve the status of a notification.
  • POST /notifications/schedule: Schedule a notification for future delivery.
  • GET /notifications/logs: Retrieve logs of sent notifications.

4. Data model & storage

Datastores:

  • Metadata DB (SQL): Stores user preferences, notification templates, and scheduling information. Chosen for its ACID properties and structured data requirements.
  • Logs DB (NoSQL): Stores logs of sent notifications. Chosen for its scalability and ability to handle large volumes of unstructured data.

Key Tables:

  • UserPreferences: user_id, preferred_channel, email, phone_number.
  • NotificationTemplate: template_id, content, channel.
  • ScheduledNotifications: notification_id, user_id, template_id, scheduled_time.

Partition Key:

  • For ScheduledNotifications, use user_id to distribute load evenly.

5. Deep dive

The core of the notification system is the reliable delivery of messages through various channels. This involves using a message queue to decouple the sending process and ensure reliability.

sequenceDiagram
    participant Client
    participant API
    participant Queue
    participant Worker
    participant Channel

    Client->>API: POST /notifications
    API->>Queue: Enqueue notification
    loop Process notifications
        Queue->>Worker: Dequeue notification
        Worker->>Channel: Send notification (e.g., email/SMS)
        Channel-->>Worker: Acknowledge receipt
        Worker->>API: Update notification status
    end
Diagram

6. Scale, bottlenecks & trade-offs

Scalability:

  • Use a message queue (e.g., Pub/Sub) to handle high throughput and decouple the processing of notifications from their creation.
  • Horizontal scaling of workers to handle increased load.

Bottlenecks:

  • The message queue can become a bottleneck if not properly scaled or if message processing is slow.
  • Network latency can affect real-time notification delivery.

Trade-offs:

  • Consistency vs. Availability: Opt for eventual consistency in notification delivery to ensure high availability.
  • Push vs. Pull: Use a push model for immediate notifications and a pull model for scheduled notifications.
  • SQL vs. NoSQL: Use SQL for structured data with strong consistency needs and NoSQL for unstructured log data requiring high write throughput.

Failure Modes:

  • Implement retries with exponential backoff for failed notifications.
  • Use logging and monitoring to detect and resolve issues promptly.
System designEasyGoogle (Alphabet)

14. Design a URL shortening service like goo.gl.

The full question

Design a URL shortening service like goo.gl. What are the key components?

Model answer

1. Requirements & scale

Functional Requirements:

  • Shorten a given URL.
  • Redirect users from a short URL to the original URL.
  • Track the number of times a short URL is accessed.
  • Provide an API for URL shortening and redirection.

Non-Functional Requirements:

  • High availability and low latency.
  • Scalability to handle millions of URL shortening requests and redirections.
  • Reliability and fault tolerance to ensure data is not lost.

Estimates:

  • Assume 100 million new URLs per month, which is about 38 URLs per second.
  • Assume 1 billion redirections per month, which is about 385 redirections per second.
  • URL storage: If each URL entry is approximately 500 bytes, storing 100 million URLs would require around 50 GB per month.

2. High-level architecture

flowchart TD
    subgraph Client
        A[User]
    end
    subgraph Edge/CDN
        B[CDN]
    end
    subgraph Load Balancer
        C[Load Balancer]
    end
    subgraph API / Services
        D[URL Shortening Service]
        E[Redirection Service]
    end
    subgraph Cache
        F[Cache (Redis)]
    end
    subgraph Datastores
        G["SQL DB"]
        H["NoSQL DB"]
    end
    subgraph Message Queue
        I[Queue]
    end
    subgraph Workers
        J[Analytics Worker]
    end

    A -->|Shorten URL Request| B
    B --> C
    C -->|API Request| D
    D -->|Store URL| G
    D -->|Generate Short URL| H
    A -->|Redirection Request| B
    B --> C
    C -->|Fetch Original URL| E
    E -->|Check Cache| F
    F -->|Cache Miss| H
    E -->|Redirect| A
    E -->|Log Access| I
    I --> J
    J -->|Update Analytics| G
Diagram

3. API design

  • POST /shorten: Accepts a long URL and returns a shortened URL.
  • GET /{shortUrl}: Redirects to the original URL associated with the short URL.
  • GET /analytics/{shortUrl}: Returns access statistics for a given short URL.

4. Data model & storage

Datastores:

  • SQL Database: Used for storing user data and analytics due to its ACID properties.
  • NoSQL Database: Used for storing URL mappings for scalability and quick access.

Key Tables:

  • URL_Mappings:
  • short_url (Primary Key)
  • original_url
  • created_at
  • URL_Analytics:
  • short_url (Foreign Key)
  • access_count
  • last_accessed

Partitioning:

  • Use the short_url as the partition key in the NoSQL database to evenly distribute load.

5. Deep dive

The core functionality of a URL shortening service is generating a unique short URL for a given long URL. This can be efficiently achieved using a base conversion algorithm. Here's a sequence diagram illustrating the URL shortening process:

sequenceDiagram
    participant User
    participant ShorteningService
    participant SQLDB
    participant NoSQLDB

    User->>ShorteningService: POST /shorten
    ShorteningService->>NoSQLDB: Check if URL exists
    NoSQLDB-->>ShorteningService: URL not found
    ShorteningService->>ShorteningService: Generate short URL
    ShorteningService->>NoSQLDB: Store short URL mapping
    ShorteningService->>SQLDB: Log URL creation
    ShorteningService-->>User: Return short URL
Diagram

The service generates a unique identifier for each URL using a base-62 encoding of a sequential ID or a hash function. This identifier is then stored in the NoSQL database along with the original URL.

6. Scale, bottlenecks & trade-offs

Scaling:

  • Use horizontal scaling for both the NoSQL and SQL databases to handle increased load.
  • Implement read replicas for the SQL database to distribute read traffic.

Caching:

  • Use Redis to cache frequently accessed URL mappings, reducing database load and improving latency.

Bottlenecks:

  • The primary bottleneck could be the database writes during peak times. Implementing a message queue can help by decoupling the write operations.

Trade-offs:

  • Consistency vs. Availability: Using eventual consistency for URL mappings in NoSQL ensures high availability but may result in stale data for a short period.
  • Push vs. Pull: Use a push model for analytics updates to ensure timely data processing.

By carefully managing these components and trade-offs, the URL shortening service can achieve the desired scalability and performance.

System designEasyGoogle (Alphabet)Data ScientistOnsite

15. You are a Data Scientist supporting a large consumer product (e.g., YouTube).

The full question

You are a Data Scientist supporting a large consumer product (e.g., YouTube). Engineering ships a change intended to reduce client-side / video-start latency by roughly 100 ms for some users, but the new code path might increase the error rate and change buffering behavior. Design and analyze the measurement program for this change.

  1. Experiment design (latency → business impact). Propose an A/B test to estimate the causal impact of reduced latency on user engagement. Define:
  • A hypothesis and a primary metric (one decision metric), explaining why it is sensitive to latency and the sensitivity-vs-business-relevance tradeoff.
  • Diagnostic metrics to localize where any change comes from (e.g., funnel steps, latency percentiles).
  • Guardrail metrics (quality / reliability / revenue) to avoid shipping a regression — in particular playback error rate and rebuffering, since the new stack may be unstable.
  1. Unit of randomization & interference. Choose user vs. device vs. session/request-level randomization and justify it. Explain how you avoid contamination and interference (sticky bucketing, CDN/cache routing, cross-device spillover).
  2. Power / MDE / duration. Describe how you would estimate sample size and runtime: what inputs you need, how you set the MDE, and how you handle heavy-tailed watch-time. Note relevant variance drivers (user heterogeneity, seasonality, outliers).
  3. Variance reduction. Give at least two techniques to reduce variance / improve sensitivity and explain when each is appropriate (e.g., CUPED, stratification, triggering, winsorization, clustered standard errors).
  4. Analysis plan & conflicting movements. Specify the estimator, how you handle multiple metrics and heterogeneity (e.g., WiFi vs. cellular), and how you decide when results conflict — e.g., watch time is up but the error guardrail is also up.
  5. Diagnosing a ratio-metric change. Suppose leadership tracks a ratio metric such as CTR = clicks / impressions or conversion rate = purchases / sessions, and it moved by +0.3%. Outline a structured approach to diagnose why it changed, decompose the move into numerator vs. denominator effects, and guard against misleading interpretations such as Simpson’s paradox.
  6. When randomization is not possible (propensity score matching). Now assume you cannot randomize the latency change (e.g., it rolled out selectively due to infra constraints) and you only observe that some users experienced lower latency than others. Describe how you would use propensity score matching (PSM) to estimate the impact, list the assumptions PSM requires, and explain how you would validate / sensitivity-test them.

Assumptions

  • Users are global; traffic varies by time-of-day and day-of-week, and latency effects may be heterogeneous by network type (WiFi vs. cellular).
  • You can define a pre-period to compute baselines / covariates.
  • Logging is available for latency, exposure, errors, buffering, and key engagement outcomes.
  • Use a consistent reporting timezone (e.g., UTC) for daily metrics to avoid boundary artifacts.

Model answer

1. Experiment design (latency → business impact)

  • Hypothesis: Reducing client-side video-start latency by 100 ms will increase user engagement, measured by watch time per session.
  • Primary Metric:
  • Watch Time per Session: This metric is sensitive to latency because faster video starts can lead to higher engagement, as users are less likely to abandon videos that load quickly. The tradeoff is that while latency impacts user experience, other factors (e.g., content quality) also significantly influence watch time.
  • Diagnostic Metrics:
  • Funnel Steps: Track user drop-off rates at each stage (e.g., video start, video completion).
  • Latency Percentiles: Analyze 50th, 90th, and 95th percentiles to identify how latency affects different user segments.
  • Guardrail Metrics:
  • Playback Error Rate: Monitor the percentage of videos that fail to play.
  • Rebuffering Rate: Track the frequency of rebuffering events during playback.
  • Revenue Impact: Measure any changes in ad revenue or subscription metrics to ensure financial stability.

2. Unit of randomization & interference

  • Unit of Randomization: User-level randomization is preferred to ensure that each user experiences either the control or treatment condition consistently across sessions.
  • Justification:
  • User-level randomization minimizes contamination, as users will not switch between conditions during the same session.
  • Avoiding Contamination:
  • Sticky Bucketing: Assign users to a group at the first exposure and maintain that assignment throughout the experiment.
  • CDN/Cache Routing: Ensure that users are directed to the appropriate version of the application based on their assigned group.
  • Cross-Device Spillover: Limit users to a single device for the duration of the experiment to prevent effects from different devices.

3. Power / MDE / duration

  • Estimating Sample Size:
  • Inputs needed: baseline watch time, expected effect size (MDE), desired power (e.g., 80%), and significance level (e.g., 0.05).
  • Setting the MDE:
  • Based on historical data, set a Minimum Detectable Effect (MDE) of 5% increase in watch time.
  • Handling Heavy-Tailed Watch-Time:
  • Use log transformation or non-parametric methods to stabilize variance and reduce the influence of outliers.
  • Variance Drivers:
  • User heterogeneity (different engagement levels), seasonality (time of year), and outliers (extremely high or low watch times).

4. Variance reduction

  • Techniques:
  • CUPED: Use pre-experiment data to adjust for baseline watch time, improving sensitivity by controlling for variance.
  • When to Use: Effective when historical data is available and correlated with the outcome.
  • Stratification: Group users by key characteristics (e.g., network type) before randomization to ensure balanced groups.
  • When to Use: Useful when known covariates significantly impact the outcome.

5. Analysis plan & conflicting movements

  • Estimator: Use a linear regression model with robust standard errors to estimate the treatment effect on watch time while controlling for confounders.
  • Handling Multiple Metrics:
  • Apply a Bonferroni correction to adjust for multiple comparisons when analyzing guardrail metrics.
  • Deciding on Conflicts:
  • If watch time increases but error rates also rise, prioritize guardrail metrics. Investigate the root cause of errors before concluding the treatment's success.

6. Diagnosing a ratio-metric change

  • Structured Approach:
  • Decompose the CTR change into numerator (clicks) and denominator (impressions) effects.
  • Steps: 1. Analyze changes in clicks: Identify if the increase in clicks is due to more effective ads or increased impressions. 2. Analyze changes in impressions: Determine if there was a change in the number of impressions served.
  • Guarding Against Misleading Interpretations:
  • Use stratified analysis to check for Simpson’s paradox, ensuring that the observed changes are not driven by confounding factors.

7. When randomization is not possible (propensity score matching)

  • Using Propensity Score Matching (PSM):
  • Match users who experienced lower latency with similar users who did not based on observed covariates (e.g., demographics, historical engagement).
  • Assumptions Required:
  • Ignorability: All confounding variables are observed and included in the model.
  • Overlap: There is sufficient overlap in propensity scores between treated and control groups.
  • Validation/Sensitivity Testing:
  • Conduct balance checks on covariates post-matching to ensure groups are comparable.
  • Perform sensitivity analysis to assess how robust the results are to potential unobserved confounding.
System designEasyGoogle (Alphabet)Software Engineer

16. What considerations would you make when designing a RESTful API?

Model answer

1. Requirements & scale

When designing a RESTful API, it's essential to consider both functional and non-functional requirements:

Functional Requirements:

  • CRUD Operations: The API should support Create, Read, Update, and Delete operations for resources.
  • Resource Identification: Each resource should be uniquely identifiable via a URI.
  • Statelessness: Each request from the client to the server must contain all the information needed to understand and process the request.
  • Data Formats: Support for JSON and XML as data interchange formats.

Non-Functional Requirements:

  • Scalability: The API should handle increasing loads efficiently.
  • Performance: Low latency and high throughput are critical.
  • Security: Implement authentication and authorization mechanisms.
  • Reliability: The API should be highly available and fault-tolerant.
  • Versioning: Support for versioning to ensure backward compatibility.

Back-of-the-envelope Estimates:

  • QPS (Queries Per Second): Estimate based on expected user base and operations. For example, if expecting 10,000 users with each making 5 requests per second, the API should handle 50,000 QPS.
  • Storage: Depends on the data model and expected data growth. For instance, if each resource is 1KB and there are 1 million resources, storage needs would be approximately 1GB.
  • Bandwidth: Calculate based on average response size and QPS. If the average response is 2KB, then bandwidth = 50,000 QPS * 2KB = 100MB/s.

2. High-level architecture

flowchart TD
    subgraph Client
        A[User]
    end
    subgraph Edge/CDN
        B[CDN]
    end
    subgraph Load Balancer
        C[Load Balancer]
    end
    subgraph API / Services
        D[API Gateway]
        E[Auth Service]
        F[Resource Service]
    end
    subgraph Cache
        G[Redis Cache]
    end
    subgraph Datastores
        H["SQL DB"]
        I["NoSQL DB"]
    end
    subgraph Message Queue
        J[Message Queue]
    end
    subgraph Workers
        K[Background Worker]
    end

    A -->|HTTP Request| B
    B -->|Cached Content| A
    B -->|HTTP Request| C
    C -->|Route Request| D
    D -->|Auth Check| E
    E -->|Valid/Invalid| D
    D -->|Forward Request| F
    F -->|Read/Write| G
    G -->|Cache Hit/Miss| F
    F -->|DB Query| H
    F -->|DB Query| I
    F -->|Async Task| J
    J -->|Process Task| K
Diagram

3. API design

Key endpoints for a RESTful API might include:

  • GET /resources: Retrieve a list of resources.
  • POST /resources: Create a new resource.
  • GET /resources/{id}: Retrieve a specific resource by ID.
  • PUT /resources/{id}: Update a specific resource by ID.
  • DELETE /resources/{id}: Delete a specific resource by ID.
  • GET /resources/{id}/related: Retrieve related resources.

4. Data model & storage

Chosen Datastores:

  • SQL Database: For structured data requiring ACID transactions, such as user information and resource metadata.
  • NoSQL Database: For unstructured or semi-structured data, such as logs or user-generated content.

Key Tables:

  • Users Table (SQL): UserID (Primary Key), Username, Email, PasswordHash.
  • Resources Table (SQL): ResourceID (Primary Key), UserID (Foreign Key), Data, Timestamp.
  • Logs Collection (NoSQL): LogID, UserID, Action, Timestamp.

Partition/Sharding Key:

  • UserID for user-specific data to distribute load evenly across database shards.

5. Deep dive

The core of a RESTful API is its ability to handle requests statelessly and efficiently. A typical request flow involves:

sequenceDiagram
    participant User
    participant CDN
    participant LoadBalancer
    participant APIGateway
    participant AuthService
    participant ResourceService
    participant SQLDB
    participant RedisCache

    User->>CDN: HTTP Request
    CDN-->>User: Cached Response (if available)
    CDN->>LoadBalancer: HTTP Request
    LoadBalancer->>APIGateway: Route Request
    APIGateway->>AuthService: Verify Token
    AuthService-->>APIGateway: Auth Result
    APIGateway->>ResourceService: Forward Request
    ResourceService->>RedisCache: Check Cache
    RedisCache-->>ResourceService: Cache Miss
    ResourceService->>SQLDB: Query Data
    SQLDB-->>ResourceService: Return Data
    ResourceService->>RedisCache: Update Cache
    ResourceService-->>APIGateway: Response
    APIGateway-->>User: HTTP Response
Diagram

6. Scale, bottlenecks & trade-offs

Replication and Sharding:

  • Use database replication for read scalability and high availability.
  • Shard databases based on UserID to distribute load and improve write performance.

Caching:

  • Implement caching at multiple levels (CDN, Redis) to reduce latency and load on the database.

Single Points of Failure:

  • Use redundant load balancers and database replicas to avoid single points of failure.

Trade-offs:

  • Consistency vs. Availability (CAP Theorem): Choose eventual consistency for non-critical data to improve availability.
  • Push vs. Pull: Use pull-based mechanisms for client updates to reduce server load.
  • Sync vs. Async: Use asynchronous processing for non-critical tasks to improve response times.

By carefully considering these aspects, a robust, scalable, and efficient RESTful API can be designed to meet both current and future needs.

TechnicalEasyGoogle (Alphabet)Data ScientistTechnical screen

17. What is the probability that a seven-game series goes to 7 games?

Model answer

The flow

  1. Identify the distribution: Recognize the series as a sequence of independent Bernoulli trials.
  2. Define the event: Determine the condition for the series to reach 7 games.
  3. Write the formula: Use the binomial distribution to calculate the probability.
  4. Compute the probability: Perform the arithmetic with plausible numbers.
  5. State implications: Discuss what the result implies and potential limitations.

The answer

1. Identify the distribution: A seven-game series can be modeled as a sequence of independent Bernoulli trials, where each trial represents a game and can result in either a win or a loss for a particular team.

2. Define the event: For the series to go to 7 games, each team must win exactly 3 games in the first 6 games, forcing a decisive 7th game.

3. Write the formula: The probability that the series goes to 7 games is determined by the binomial distribution: $$ P(\text{7 games}) = \binom{6}{3} \cdot p^3 \cdot (1-p)^3 $$ where $p$ is the probability of one team winning a single game.

4. Compute the probability: Assume $p = 0.5$, meaning each team has an equal chance of winning any given game. $$ P(\text{7 games}) = \binom{6}{3} \cdot (0.5)^3 \cdot (0.5)^3 $$ $$ P(\text{7 games}) = 20 \cdot (0.125) \cdot (0.125) $$ $$ P(\text{7 games}) = 20 \cdot 0.015625 $$ $$ P(\text{7 games}) = 0.3125 $$ Therefore, the probability that the series goes to 7 games is 31.25%.

5. State implications: This calculation implies that in a fair series, there is a 31.25% chance it will go to the full 7 games. This model assumes each game is independent and the teams are evenly matched. If one team is significantly stronger, the probability would decrease. Additionally, this model does not account for external factors like home-court advantage.

Why this works

  • Understanding of distributions: The interviewer is testing your ability to recognize and apply the correct statistical distribution for a given scenario.
  • Mathematical accuracy: A strong answer demonstrates precise calculation and correct application of the binomial formula.
  • Logical reasoning: Explaining the implications and limitations shows a deeper understanding of the model's assumptions.
  • Common pitfalls: Weak answers might misidentify the distribution, incorrectly compute the probability, or fail to discuss the model's assumptions and limitations.
TechnicalEasyGoogle (Alphabet)Data ScientistTechnical Screen

18. You have a single numeric observation and want to know if it was drawn from a standard normal distribution.

The full question

You have a single numeric observation and want to know if it was drawn from a standard normal distribution.

Question

Which statistical test would you apply to decide whether that single observation comes from a normal distribution? State the null and alternative hypotheses and the decision rule.

Hints

Compute a z-score and compare it to critical values of the standard normal.

Model answer

To determine if a single numeric observation comes from a standard normal distribution, we can use the concept of a z-score. Although statistical tests typically require a sample of data, with a single observation, we can still assess its likelihood of being drawn from a standard normal distribution by computing its z-score and comparing it to critical values.

Steps to Determine if the Observation is from a Standard Normal Distribution

  1. Compute the Z-Score: - For a standard normal distribution, the mean (\(\mu\)) is 0 and the standard deviation (\(\sigma\)) is 1. - The z-score for the observation \(x\) is calculated as: \[ z = \frac{x - \mu}{\sigma} = x \] - Since \(\mu = 0\) and \(\sigma = 1\), the z-score is simply the value of the observation itself.
  2. State the Hypotheses: - Null Hypothesis (\(H_0\)): The observation is from a standard normal distribution. - Alternative Hypothesis (\(H_a\)): The observation is not from a standard normal distribution.
  3. Decision Rule: - Choose a significance level (\(\alpha\)), commonly 0.05. - Determine the critical z-values for a two-tailed test at the chosen \(\alpha\). For \(\alpha = 0.05\), the critical values are approximately -1.96 and 1.96. - Decision: - If the computed z-score falls between -1.96 and 1.96, we fail to reject the null hypothesis (\(H_0\)). - If the z-score is less than -1.96 or greater than 1.96, we reject the null hypothesis (\(H_0\)).

Example

  • Suppose the observation \(x = 1.5\).
  • Compute the z-score: \(z = 1.5\).
  • Compare \(z\) to the critical values:
  • Since \(1.5\) is between -1.96 and 1.96, we fail to reject the null hypothesis.

Conclusion

  • Fail to Reject \(H_0\): The observation is consistent with being drawn from a standard normal distribution.
  • Reject \(H_0\): The observation is unlikely to have been drawn from a standard normal distribution.

This approach provides a basic method to assess a single observation's likelihood of coming from a standard normal distribution, using the properties of the z-score and critical values.

TechnicalEasyGoogle (Alphabet)Engineering Manager

19. What is your experience with programming languages?

Model answer

How I would answer

I would be specific about languages I have used, how deeply I used them, and the decisions I made—not just list technologies. I would tailor the examples below to my actual experience rather than claim proficiency I cannot support.

  1. Lead with the strongest evidence. “My deepest experience is with [language]. I used it for [product or service] over [time period], where I was responsible for [design, delivery, or technical leadership].” State whether your experience is hands-on, review-level, or primarily team oversight.
  2. Add a contrasting example. “I have also used [second language] for [specific use case]. We chose it because [ecosystem, performance, team expertise, or maintainability], while accepting [trade-off].” This shows judgment rather than language advocacy.
  3. Explain how you evaluate languages. I consider runtime and performance needs, libraries and tooling, hiring and team familiarity, interoperability, operational support, and the cost of maintaining another stack. For a new service, I would usually prefer an existing supported language unless a measurable requirement justifies introducing one.
  4. Show Engineering Manager scope. Describe how you set standards, support code reviews and mentoring, and ensure teams can make local choices within platform and security guardrails. Explain how you avoid making yourself the sole expert or turning a preference into an organizational mandate.
  5. Close with a measurable example. “In [project], we selected [language] because [reason]. We measured [latency, reliability, delivery time, defect rate, or operational cost] and reviewed the choice after [milestone].” Use real numbers only if you can explain their source and context.

What interviewers listen for

  • Honest calibration of proficiency and a concrete example of impact.
  • Ability to connect language choice to product and operational constraints.
  • A balance between consistency and team autonomy.
  • Evidence that you can lead engineers across stacks without micromanaging implementation.
TechnicalEasyGoogle (Alphabet)

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

Model answer

Difference Between a Stack and a 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 implies that the first element added to the queue will be the first one to be removed.
  2. Operations: - Stack: - Push: Add an element to the top of the stack. - Pop: Remove the element from the top of the stack. - Peek/Top: Retrieve the element at the top 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/Peek: Retrieve the element at the front of the queue without removing it.
  3. Use Cases: - Stack: Used in scenarios like function call management (call stack), undo mechanisms in text editors, and syntax parsing. - Queue: Used in scenarios like scheduling processes in operating systems, handling requests in web servers, and breadth-first search in graphs.
  4. Implementation: - Both stacks and queues can be implemented using arrays or linked lists. However, the choice of implementation can affect the complexity of operations like insertion and deletion.
  5. Complexity: - Stack: Both push and pop operations generally have a time complexity of O(1). - Queue: Both enqueue and dequeue operations generally have a time complexity of O(1), especially when implemented using a linked list or a circular buffer.

Understanding these differences is crucial for selecting the appropriate data structure based on the specific requirements of a problem, ensuring efficient data management and processing.

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