Python interview prep
Python interview questions, from your first round to FAANG
156 questions in three levels. Write real Python in your browser, run it against visible and hidden test cases, then do what interviewers actually score: analyse the time and space complexity, measure it, optimise it and explain it — with Solvi, the AI coach, one click away.
The nine steps every question trains
Getting the right output is step three of nine. Each question page tracks these for you — several tick themselves as you run, measure and submit.
- 01
Understand
Restate it. Ask about input size and edge cases.
- 02
Brute force
Get something correct before something clever.
- 03
Correct output
Run the examples until they pass.
- 04
Time complexity
Count the work as n grows.
- 05
Space complexity
Count the extra memory.
- 06
Bottleneck
Find the line that dominates.
- 07
Optimise
Usually a set, a dict, two pointers or a heap.
- 08
Explain
Say why the optimisation works.
- 09
Edge cases
Empty, one element, duplicates, negatives.
Example — intersection of two lists. The first version checks x in list2 for every element: O(n × m). The bottleneck is that membership test. Turn list2 into a set and each lookup becomes O(1), so the whole thing is O(n + m). That “solve → analyse → optimise → explain” story is the answer. Try it →
Interactive
Feel the difference Big-O makes
Drag n. Bars are on a log scale — each grid step is 10× more work.
- O(1)≈ < 1 µs
dict lookup, list[i], append · 1 step
- O(log n)≈ < 1 µs
binary search, heap push · 10 steps
- O(n)≈ 20 µs
one loop, x in list, sum() · 1,000 steps
- O(n log n)≈ 199 µs
sorted(), merge sort · 9,966 steps
- O(n²)≈ 20.0 ms
nested loops over the input · 1.0 × 10^6 steps
- O(2ⁿ)≈ longer than the universe
every subset, naive recursion · > 10³⁰ steps
Times assume about 50 million simple operations per second, a rough figure for CPython. Real code has constants Big-O ignores — what it predicts reliably is how cost grows.
Python time complexity cheat sheet
Most “why is this slow?” answers in an interview come from this table. CPython, average case.
| Operation | Cost | Why it matters |
|---|---|---|
| list[i], list[i] = x, len(list) | O(1) | Arrays of pointers — indexing is direct. |
| list.append(x), list.pop() | O(1) amortised | Occasional resize, spread over many appends. |
| list.insert(0, x), list.pop(0) | O(n) | Every other element shifts. Use collections.deque. |
| x in list, list.index(x), list.count(x) | O(n) | A linear scan — the most common hidden O(n²). |
| x in set, set.add(x), dict[k], k in dict | O(1) average | Hash tables. Worst case O(n), almost never seen. |
| sorted(xs), list.sort() | O(n log n) | Timsort; stable; O(n) on already-sorted data. |
| heapq.heappush / heappop | O(log n) | A binary heap in a list. heapq.heapify is O(n). |
| deque.append / appendleft / popleft | O(1) | The right queue. Indexing the middle is O(n). |
| s + t, s[a:b], list(xs), xs[:] | O(k) | Copies k elements — slicing in a loop adds up. |
| "".join(parts) | O(total length) | Build strings this way, not with += in a loop. |
| bisect.bisect_left(sorted_xs, x) | O(log n) | Binary search; insort is O(n) because of the insert. |
| Counter(xs), set(xs), dict.fromkeys(xs) | O(n) | One pass, O(n) memory. |
The roadmap
Work top to bottom, or jump to the topic you are weakest in. Progress is saved on this device.
Foundations
Freshers and first Python interview · 30 questions
Numbers & loops
Conditions, loops, digit tricks and your first O(1)-vs-O(n) comparison.
- ✓FizzBuzz in PythonO(n)
- ✓Check If a Number Is Prime in PythonO(√n)
- ✓Sum of the Digits of a NumberO(log n)
- ✓Reverse the Digits of an IntegerO(log n)
- ✓Check If a Number Is a PalindromeO(log n)
- ✓Check an Armstrong NumberO(log n)
- ✓GCD With the Euclidean AlgorithmO(log n)
- ✓Check If a Year Is a Leap YearO(1)
- ✓Count the Digits in a NumberO(log n)
- ✓Convert Decimal to BinaryO(log n)
- ✓Check If a Number Is a Power of TwoO(1)
- ✓Sum of the First N Natural NumbersO(1)
Text basics
Iterating strings, counting, splitting and building new strings.
List basics
Max, min, search and the jump from linear to logarithmic.
- ✓Find the Largest Number Without max()O(n)
- ✓Find Min and Max in One PassO(n)
- ✓Sum a List Without sum()O(n)
- ✓Average of a List of NumbersO(n)
- ✓Count Occurrences of an ElementO(n)
- ✓Check If a List Is SortedO(n)
- ✓Separate Even and Odd NumbersO(n)
- ✓Linear Search in PythonO(n)
- ✓Binary Search in PythonO(log n)
- ✓Reverse a List In PlaceO(n)
Working engineer
2–6 years, product and data teams · 95 questions
Lists & arrays
Single-pass scans, two pointers, hashing to beat nested loops.
- ✓1.Second Largest Number Without SortingO(n)
- ✓2.Remove Duplicates, Keep Original OrderO(n)
- ✓3.Duplicate Elements and Their CountsO(n)
- ✓4.Find the Missing Number from 1 to NO(n)
- ✓5.Find All Pairs That Sum to a TargetO(n)
- ✓6.Move All Zeros to the EndO(n)
- ✓7.Rotate a List Right by K StepsO(n)
- ✓8.Intersection of Two ListsO(n + m)
- ✓9.Union of Two Lists Without DuplicatesO(n + m)
- ✓10.Maximum Subarray Sum (Kadane's Algorithm)O(n)
- ✓11.Find the Element That Appears OnceO(n)
- ✓12.Merge Two Sorted ListsO(n + m)
- ✓13.Top K Largest ElementsO(n log k)
- ✓14.Common Elements in Three ListsO(n + m + p)
- ✓15.Flatten a Nested List (One Level)O(n)
Strings
Immutability, counting, sliding windows and run-length encoding.
- ✓16.First Non-Repeating CharacterO(n)
- ✓17.First Repeating Character in a StringO(n)
- ✓18.Check If Two Strings Are AnagramsO(n)
- ✓19.Check If a String Is a PalindromeO(n)
- ✓20.Reverse a String Without SlicingO(n)
- ✓21.Count Character Frequency in a StringO(n)
- ✓22.Find the Longest Word in a SentenceO(n)
- ✓23.Remove Duplicate Characters from a StringO(n)
- ✓24.Longest Substring Without Repeating CharsO(n)
- ✓25.Find All Occurrences of a SubstringO(n·m)
- ✓26.String Compression (Run-Length Encoding)O(n)
Dictionaries & hashing
Frequency maps, grouping keys and O(1) lookups.
- ✓27.Word Frequency CountO(n)
- ✓28.Group Anagrams TogetherO(n·k log k)
- ✓29.Two Sum Using a DictionaryO(n)
- ✓30.Most Frequent Element in a ListO(n)
- ✓31.Merge Two Dictionaries in PythonO(n + m)
- ✓32.Invert a Dictionary (Swap Keys and Values)O(n)
- ✓33.Find All Keys With the Maximum ValueO(n)
- ✓34.Find Duplicate Values in a DictionaryO(n)
- ✓35.Implement a Simple Key-Value CacheO(1)
Sets
Membership, set algebra and the O(n) consecutive-run trick.
Stacks & queues
LIFO/FIFO, monotonic stacks and amortised analysis.
Recursion
Base cases, memoization, backtracking and exponential growth.
Python internals
Decorators, generators, iterators, copying, mutability and the classic traps.
- ✓55.List Comprehension: Filter Even NumbersO(n)
- ✓56.map, filter and reduce in PythonO(n)
- ✓57.*args and **kwargs ExplainedO(n)
- ✓58.Write a Timing DecoratorO(1)
- ✓59.Fibonacci Generator With yieldO(n)
- ✓60.List vs Tuple vs Set vs DictO(1)
- ✓61.Build a Custom Iterator (__iter__, __next__)O(1)
- ✓62.Write a Context Manager (__enter__, __exit__)O(1)
- ✓63.Create and Raise a Custom ExceptionO(1)
- ✓64.Shallow Copy vs Deep Copy in PythonO(n)
- ✓65.Mutable vs Immutable: List AliasingO(n)
- ✓66.Fix the Mutable Default Argument BugO(1)
- ✓67.is vs == in PythonO(1)
- ✓68.Decorator With Arguments (@repeat(n))O(times)
- ✓69.Sort a List of Tuples by Second ElementO(n log n)
- ✓70.Sort a List of Dictionaries by KeyO(n log n)
Object-oriented Python
Classes, inheritance, encapsulation, ABCs and design patterns.
- ✓71.BankAccount Class With Deposit and WithdrawO(1)
- ✓72.Inheritance in Python: Animal and DogO(1)
- ✓73.Method Overriding and super()O(1)
- ✓74.Encapsulation: Private Balance + @propertyO(1)
- ✓75.Abstract Base Class: Shape, Circle, RectangleO(1)
- ✓76.__str__ vs __repr__ in PythonO(1)
- ✓77.Class Variables vs Instance VariablesO(1)
- ✓78.Implement the Singleton PatternO(1)
- ✓79.Employee Management System ClassO(1)
- ✓80.Composition vs Inheritance: Car Has an EngineO(1)
Advanced L2
LRU caches, concurrency, rate limiting, streaming files and APIs.
- ✓81.Implement an LRU Cache in PythonO(1)
- ✓82.Producer-Consumer With a QueueO(n)
- ✓83.Thread-Safe Counter With a LockO(1)
- ✓84.Retry Decorator With Max AttemptsO(k)
- ✓85.Rate Limiter (Sliding Window Log)O(1) amortised
- ✓86.Parse Logs and Count Log LevelsO(n)
- ✓87.Process a CSV: Average SalaryO(n)
- ✓88.Transform JSON Data in PythonO(n)
- ✓89.Find Duplicate Files by Content HashO(n)
- ✓90.Process a Huge File Without Loading ItO(n)
- ✓91.Count ERROR Lines in a 10 GB Log FileO(n)
- ✓92.Make Concurrent API Calls With asyncioO(n)
- ✓93.Parallel CPU Work With multiprocessingO(n)
- ✓94.Build a Generator Data PipelineO(n)
- ✓95.Fetch All Pages From a Paginated APIO(p + n)
FAANG
Big-tech coding rounds · 31 questions
Two pointers
Sorted-array squeezes and the greedy argument behind them.
Sliding window & monotonic deque
Grow, shrink and never look back.
Binary search on answers
Halving on rotated arrays, partitions and predicates.
Heaps & streams
k-way merges, top-k and running medians.
Graphs
BFS, DFS, topological sort and Dijkstra.
Trees
Traversals, invariants and serialisation.
Dynamic programming
State, transition, base case — and the space optimisation.
Backtracking
Choose, explore, un-choose, prune.
Intervals & greedy
Sort by the right key, sweep once.
Data-structure design
Tries and the structures behind autocomplete.
Questions about this prep
What do L1, L2 and L3 mean?
L1 is the fresher round: loops, conditions, strings and lists. L2 is what a working engineer with a few years of experience is asked: hashing, recursion, Python internals such as decorators and generators, OOP, and practical problems like LRU caches, rate limiters, concurrency and streaming large files. L3 is the FAANG coding round: two pointers, sliding windows, binary search on rotated or partitioned arrays, heaps, graphs, trees, dynamic programming and backtracking.
Do I need to install Python?
No. Every question runs real CPython 3.13 inside your browser via WebAssembly. Your code never leaves your device, and it is saved locally as you type.
How do the test cases work?
Run executes the visible examples. Submit runs every test, including hidden edge cases such as empty input, duplicates and negatives. Each result shows the input, the expected output, your output, anything you printed and how long it took.
How do I learn time and space complexity here?
Every question has a Complexity Lab: you commit to a Big-O for time and space, see the optimal answer and why, then measure your own code, the optimal solution and the brute force at growing input sizes and watch the curves. The roadmap also has an interactive Big-O explorer and a cheat sheet of Python operation costs.
What does the Solvi AI coach do?
Solvi is the floating assistant on every question. It sees your code and your failing tests, explains the problem, gives one hint at a time, explains errors, estimates the complexity of your code and can play the interviewer for a mock explanation. It will not write the full solution for you — that is behind the Reveal button.
Are the questions free?
Yes. All questions, solutions, the Complexity Lab and the Solvi coach are free.
New to Python itself? Start with the free Python handbook, or practise data-engineering Python on /practice.
