Python Interview Questions 2026
59 Python interview questions from Amazon, Google, Swiggy, Meta. All difficulty levels, all roles. Upvoted by engineers who were asked them.
Python Questions by Company
Amazon (5)
Given an array of integers and a target sum, return all unique triplets that sum to the target. Discuss time and space complexity. Then extend the problem to k-sum and analyze how recursion depth changes performance for large k.
Given an array of integers, find the length of the longest subarray with a sum equal to zero. Explain the prefix sum + HashMap approach and why the naive O(n2) solution is unacceptable for large inputs.
Serialize and deserialize a binary tree. Implement both functions and explain why BFS serialization makes deserialization simpler than DFS. What is the time and space complexity?
You have a Spark job that ingests 500GB of clickstream data daily. It is failing with OOM errors on the executor. How do you debug and fix it?
Explain how Python's dictionary achieves average O(1) lookup. What happens internally when two keys hash to the same bucket?
Google (5)
Given a binary tree, return the boundary of the tree in anti-clockwise direction starting from the root. The boundary consists of the left boundary, leaves, and the right boundary in reverse.
Implement a topological sort for a directed acyclic graph. Then extend it to detect cycles and explain how this maps to dependency resolution in build systems like Bazel.
Given a list of intervals, merge all overlapping intervals and return the result. Explain the sort-then-scan approach and the edge cases (touching intervals, single interval, all disjoint).
Our RAG pipeline responses are accurate in staging but hallucinate in production on long user queries. Walk me through how you debug and fix this.
You have a 50GB CSV file and only 8GB of RAM. Walk through how you would compute the average of one column using pandas without crashing the process.
Swiggy (3)
Given a list of delivery time windows for N restaurants, find the maximum number of restaurants whose windows overlap at any point in time. Explain the sweep-line approach, time complexity, and how this maps to capacity planning for Swiggy's logistics team.
Implement a rate limiter for Swiggy's API gateway using the token bucket algorithm. Handle 1000 requests/second per user. Code the solution and explain how you'd deploy it across multiple API servers with Redis.
Given delivery time estimates for N restaurants, find the restaurant with the minimum average delivery time across all its orders. Handle ties and explain your data structure choices.
Meta (5)
Given Meta's social graph, find all friend-of-friend recommendations for a user that are not already friends. Discuss BFS at scale, how to prune the search space, and how to rank recommendations by mutual friend count efficiently.
Given a social graph, find all users within K hops of a given user. Implement BFS with a visited set. Then discuss how you would scale this to Meta's 3 billion user graph using partitioning.
Given an array of N integers, find the maximum product subarray. Explain why you need to track both the maximum and minimum product ending at each position, and handle zeros and negative numbers.
Your fine-tuned LLM performs well on your eval set but users report degraded responses 2 weeks after deployment. What is happening and what do you do?
What is the difference between RANK(), DENSE_RANK(), and ROW_NUMBER()? Give a real use case for each.
Zomato (2)
Given a list of restaurant ratings and a minimum threshold, return the top-k restaurants sorted by rating using a min-heap. Explain why a heap beats a full sort for large k, and the time complexity of both approaches.
How does Zomato calculate a restaurant's "delivery fee"? The fee depends on distance, demand, time of day, and partner availability. Implement a pricing function given these inputs and discuss fairness trade-offs.
Microsoft (5)
Given a binary tree, print nodes level by level (BFS traversal). Then modify it to print alternate levels in reverse order (zigzag traversal). Analyse time and space complexity.
Given a 2D grid of 0s and 1s, count the number of islands. Then extend: find the largest island, and then explain how you would solve this for a streaming grid that changes in real time using a Union-Find structure.
Find all pairs in an array that sum to a given target value. Explain the HashSet approach for O(n) time, handle duplicate pairs correctly, and discuss edge cases (negative numbers, empty array).
You are building an AI agent that books travel. It has access to 6 tools. How do you prevent it from calling tools in the wrong order or entering infinite loops?
Write a Python decorator @timed that prints how long a function took to execute, and explain how functools.wraps prevents it from breaking introspection.
Flipkart (1)
Given a directed graph representing category hierarchies in an e-commerce catalog, find the shortest path between two categories. Explain BFS vs Dijkstra for unweighted vs weighted graphs.
Apple (1)
Given a BST, find the closest value to a given target. Explain the O(log n) iterative approach using BST properties, and how the answer changes if the tree is unbalanced.
Netflix (2)
Given a list of movie ratings (1-5 stars) for N users, compute the Pearson correlation between two users to measure taste similarity. Explain how this feeds into collaborative filtering.
Design a data pipeline to ingest CDC (Change Data Capture) events from a MySQL database into a Snowflake data warehouse in near real-time.
Uber (5)
Given a city map as a weighted graph, find the shortest travel time from a driver's current location to all potential passenger pickup points simultaneously. How does Dijkstra's multi-source variant solve this?
Given a list of GPS coordinates representing a driver's path, compute the total distance travelled. Then find the longest contiguous segment where the driver was stationary (speed < 5 km/h). Discuss floating-point precision issues.
Your pipeline SLA requires data to be available in the warehouse by 6 AM. Yesterday it missed at 7:30 AM. Walk me through your incident response.
Your PySpark job has data skew on a join key (user_id) where 1% of users account for 60% of the data. How do you handle it?
You need to find all available drivers within a 3km radius of a rider efficiently, with millions of driver location updates per second. What indexing structure would you use and why not a naive distance calculation over all drivers?
Airbnb (3)
Given a list of bookings with start and end dates, find the minimum number of rooms needed so that no two overlapping bookings share a room. Explain the sweep-line and min-heap approaches.
How does Airbnb's dynamic pricing work? Given historical booking data, seasonality, local events, and competitor prices, how do you recommend a nightly rate that maximises host revenue? Discuss the ML pipeline.
Your team discovers that 20% of user_id values in the orders table do not match any record in the users table. How do you handle this as a data engineer?
Adobe (1)
Implement a basic version of Adobe Lightroom's non-destructive editing model. All edits (brightness, contrast, crop) are stored as a list of operations, not applied to the original image. Explain the data structure and how you apply/undo operations.
Atlassian (2)
Given a list of Jira sprint start/end dates, find all sprints that overlap with a given date range. Implement an efficient solution using interval trees or sorted arrays with binary search.
What are Airflow Sensors and when would you use a FileSensor vs an HttpSensor vs an ExternalTaskSensor?
PayU (2)
Given an array of transaction amounts, find all pairs whose sum equals a given target. Return the count of unique pairs. For example: [100, 200, 300, 400], target = 500 → pairs: (100,400), (200,300) → count: 2. What is the time and space complexity of your approach?
Given a 2D matrix representing a payment heatmap (rows = hours, columns = days), find the submatrix with the maximum sum. The submatrix represents the peak payment activity window. Describe your approach — can you do better than O(n³)?
General (5)
A file lands in AWS S3 and must be ingested into Snowflake automatically in near real-time. How would you design the solution? Explain the role of Snowpipe, event notifications, and the ingestion workflow.
Snowpipe is ingesting duplicate records from cloud storage. How would you detect, prevent, and remediate duplicate data in Snowflake?
A query that previously completed in 2 minutes now takes 20 minutes. Describe your systematic approach to troubleshooting and optimizing performance in Snowflake.
Design an end-to-end data pipeline using Python, PySpark, Snowflake, Airflow, and AWS S3. Explain data flow, orchestration, monitoring, and failure handling.
What is the difference between .loc[] and .iloc[] in pandas? Give an example where using the wrong one silently returns the wrong row.
Anthropic (1)
How would you reduce the latency of a RAG pipeline from 4 seconds to under 1 second in production?
OpenAI (1)
Explain the difference between zero-shot, few-shot, and chain-of-thought prompting. When would you choose each in production?
TikTok (1)
Design an AI content moderation system for a social platform with 10 million daily posts. How do you balance accuracy, cost, and latency?
JPMorgan (1)
What is the difference between narrow and wide transformations in Spark? Why does it matter for performance?
Walmart (1)
You need to join a 500GB transaction table with a 5MB lookup table (country codes). The join is taking 20 minutes. How do you fix it?
Cognizant (1)
What is the difference between cache() and persist() in Spark? When should you use StorageLevel.MEMORY_AND_DISK?
Siemens (1)
You have a streaming PySpark job reading from Kafka that processes IoT sensor events. Events can arrive up to 10 minutes late. How do you handle late data correctly?
Spotify (1)
Your Airflow DAG that runs at midnight has been running for 6 hours and is still not complete. SLA breached. What do you do and how do you prevent it next time?
DoorDash (1)
What is the difference between Airflow TaskFlow API (@task decorator) and traditional PythonOperator? When would you prefer each?
LinkedIn (1)
How does Airflow handle backfilling? Design a DAG that safely backfills 90 days of missing data without overloading the database.
Grab (2)
You need to run a DAG that processes 10,000 files daily — one task per file. How do you design this in Airflow without creating 10,000 static tasks?
Given an array of ride fare amounts collected over a day, find the maximum sum of any contiguous subarray of exactly k rides (a sliding window problem). Walk through the O(n) approach.
Practice these questions with AI feedback
Get instant grading on your answers, identify your weak areas, and generate a personalised 14-day study plan — all free.
Build my study plan →