Repo¶
38 cards — 🟢 6 easy | 🟡 12 medium | 🔴 6 hard
🟢 Easy (6)¶
1. 3. What is PEP 8 and why is it important?
Show answer
**PEP 8** is Python's official style guide promoting readable, consistent code.Key rules:
- 4-space indentation, 79-char line length
- `CamelCase` for classes, `snake_case` for functions/variables
- Surround operators with spaces, use blank lines to separate logical sections
- Triple-quote docstrings for documentation
It matters because consistent style reduces cognitive load when reading or contributing to code. Tools like `flake8`, `black`, and `ruff` enforce PEP 8 automatically.
2. 6. Explain the LIFO scheme.?
Show answer
Solution: LIFO is a short form of Last In First Out. It refers how data is accessed, stored and retrieved. Using this scheme, data that was stored last should be the one to be extracted first. This also means that in order to gain access to the first data, all the other data that was stored before this first data must first be retrieved and extracted.3. 2. How to find the loop or cycle in a linked list in one pass ?
Show answer
Solution: Start with two pointer `p` and `q`. For every second iteration of `p`, iterate `q`. If `p` and `q` are pointing to the same node, there is a loop or cycle present.Gotcha: Monorepo tooling (Bazel, Nx, Turborepo) is essential at scale — plain git and make struggle with thousands of packages.
4. 3. How to find the k th element from the end of a linked list in one pass ?
Show answer
Solution: Start with two pointer `p` and `q`. When the `p` pointer reahces upto the `k th` element, increment `q`.When `p` reaches the end of the list. `q` is ponting to the element 'k th' from the end.Remember: "Trunk-based = short-lived branches, frequent merges." Branches live hours to days, not weeks.
Example: Developer creates branch, makes small change, opens PR, merges same day.
5. 4. List some real world applications of linked list ?
Show answer
Solution:*Image viewer* – Previous and next images are linked, hence can be accessed by next and previous button.
*Previous and next page in web browser* – We can access previous and next url searched in web browser by pressing back and next button since, they are linked as linked list.
*Music Player* – Songs in music player are linked to previous and next song. you can play songs either from starting or ending of the list.
6. 13. Explain args_ and _*kwargs in Python.?
Show answer
`*args` collects extra positional arguments into a tuple. `**kwargs` collects extra keyword arguments into a dictionary.```python\ndef example(*args, **kwargs):\n print(args) # (1, 2, 3)\n print(kwargs) # {'key': 'value'}\nexample(1, 2, 3, key='value')\n```
Use them to write flexible functions that accept variable numbers of arguments. They are also essential for decorators and forwarding arguments to other functions.
🟡 Medium (12)¶
1. 14. What are decorators in Python?
Show answer
Decorators are functions that modify the behavior of other functions or classes. They use the `@decorator` syntax and wrap the target function.```python\n@my_decorator\ndef my_func():\n pass\n# Equivalent to: my_func = my_decorator(my_func)\n```
Common uses: logging, timing, authentication, caching (`@functools.lru_cache`), and framework features like Flask's `@app.route`. Use `@functools.wraps` inside your decorator to preserve the original function's name and docstring.
2. 15. How can you create a module in Python?
Show answer
A Python module is any `.py` file. A package is a directory with an `__init__.py` file containing modules.Create a module: write functions/classes in a `.py` file, then `import` it by filename. Create a package: make a directory, add `__init__.py`, and place modules inside.
Use `__all__` in `__init__.py` to control what `from package import *` exports. Install third-party packages with `pip install`. The `sys.path` list determines where Python searches for imports.
3. 8. What is the difference between list and tuple?
Show answer
**List**: Mutable, ordered, uses `[]`. Elements can be changed, added, or removed after creation. Slightly slower due to mutability overhead.**Tuple**: Immutable, ordered, uses `()`. Cannot be modified after creation. Faster and uses less memory.
Use tuples for fixed collections (coordinates, dict keys, function return values). Use lists when you need to modify the collection. Tuples are hashable (if contents are hashable), lists are not.
4. 9. How do you create a dictionary in Python?
Show answer
Dictionaries store key-value pairs with O(1) average lookup.```python\nd = {'name': 'Alice', 'age': 30} # literal\nd = dict(name='Alice', age=30) # constructor\nd = {k: v for k, v in pairs} # comprehension\n```
Keys must be hashable (strings, numbers, tuples). Access with `d['key']` (raises KeyError) or `d.get('key', default)`. Common methods: `.keys()`, `.values()`, `.items()`, `.update()`, `.pop()`. Since Python 3.7, dicts preserve insertion order.
5. 8. What are the minimum number of queues to implement a prioriy queue ?
Show answer
Solution: The minimum number of queues needed in this case is two. One queue is intended for sorting priorities while the other queue is used for actual storage of data.Remember: "Semantic versioning = MAJOR.MINOR.PATCH." Breaking change = major bump. New feature = minor. Bug fix = patch.
Example: Going from 2.3.1 to 3.0.0 signals breaking changes.
6. 12. What is a lambda function, and where would you use it?
Show answer
A lambda is a small anonymous function defined with `lambda args: expression`. It can take any number of arguments but only one expression.```python\nsquare = lambda x: x ** 2\nsorted(items, key=lambda x: x.name)\n```
Use lambdas for short callbacks — `sorted()`, `map()`, `filter()`, `reduce()`. For anything more complex, use a named `def` function for readability.
7. 5. What are the built-in data types in Python?
Show answer
Python's built-in data types:- **Numeric**: `int`, `float`, `complex`
- **Sequence**: `list` (mutable), `tuple` (immutable), `range`
- **Text**: `str` (immutable)
- **Mapping**: `dict`
- **Set**: `set` (mutable), `frozenset` (immutable)
- **Boolean**: `bool` (`True`/`False`, subclass of `int`)
- **Binary**: `bytes`, `bytearray`, `memoryview`
- **None**: `NoneType`
Check type with `type()`, check isinstance with `isinstance()`.
Remember: "CI = build on every commit, CD = deploy on every merge." CI catches bugs early; CD shortens the feedback loop.
8. 7. What is merge sort ?
Show answer
Solution: Merge sort, is a divide-and-conquer approach for sorting the data. In a sequence of data, adjacent ones are merged and sorted to create bigger sorted lists. These sorted lists are then merged again to form an even bigger sorted list, which continues until you have one single sorted list.9. 9. Which sorting algorithm is the fastest?
Show answer
Solution: There are many types of sorting algorithms: quick sort, bubble sort, balloon sort, radix sort, merge sort, etc. Not one can be considered the fastest because each algorithm is designed for a particular data structure and data set. It would depend on the data set that you would want to sort.10. 6. Explain the difference between a mutable and immutable object.?
Show answer
**Mutable** objects can be changed after creation (lists, dicts, sets). **Immutable** objects cannot be modified (strings, tuples, ints, frozensets).Key implications:
- Immutable objects are hashable and can be dict keys or set members
- Mutating a shared mutable object affects all references to it
- Default function arguments should not be mutable (common Python gotcha)
- Immutable objects are inherently thread-safe
11. 10. Save all leaf nodes of a Binary tree in a Doubly Linked List by using Right node as Next node and Left Node as Previous Node.?
Show answer
Convert all leaf nodes of a binary tree into a doubly linked list using the right pointer as `next` and left pointer as `prev`.Approach: Perform an inorder traversal, collecting leaf nodes. For each leaf, set `right = next_leaf` and `left = prev_leaf`. Track the head (first leaf) and use a `prev` pointer to link nodes as you traverse.
Time complexity: O(n) — visit every node once.
Space complexity: O(h) — recursion stack depth equals tree height.
12. 10. What is the difference between == and is operator in Python?
Show answer
`==` compares **values** (equality). `is` compares **identity** (same object in memory, i.e., same `id()`).```python\na = [1, 2]; b = [1, 2]\na == b # True (same content)\na is b # False (different objects)\n```
Use `is` only for singletons like `None`: `if x is None`. CPython caches small integers (-5 to 256) and interned strings, so `is` may return True for those, but do not rely on it.
🔴 Hard (6)¶
1. 4. How is memory allocation and garbage collection handled in Python?
Show answer
Python uses **reference counting** as its primary memory management: each object tracks how many references point to it, and is freed when the count drops to zero. A **cyclic garbage collector** handles circular references that reference counting cannot resolve.Memory is allocated from a private heap managed by Python's memory manager. The `gc` module lets you inspect and control garbage collection (e.g., `gc.collect()` to force a cycle). The `del` statement removes a reference but does not guarantee immediate deallocation.
2. 2. How is Python executed?
Show answer
Python code is first compiled to **bytecode** (`.pyc` files), then executed by the **Python Virtual Machine (PVM)**. This is an interpreted execution model — there is no separate compilation step visible to the user.CPython (the default interpreter) uses a **GIL** (Global Interpreter Lock) that allows only one thread to execute bytecode at a time. Alternative implementations: **PyPy** (JIT-compiled, faster), **Jython** (JVM), **IronPython** (.NET). For CPU-bound parallelism, use `multiprocessing` or native extensions to work around the GIL.
3. 7. How do you handle exceptions in Python?
Show answer
Use `try/except/else/finally` blocks:```python\ntry:\n result = risky_operation()\nexcept ValueError as e:\n handle_error(e)\nexcept (TypeError, KeyError):\n handle_other()\nelse:\n # runs if no exception\nfinally:\n # always runs (cleanup)\n```
Best practices: catch specific exceptions (never bare `except:`), use `raise` to re-raise, create custom exceptions by subclassing `Exception`, and use context managers (`with` statement) for resource cleanup.
4. 11. How does a Python function work?
Show answer
Functions are defined with `def`, can accept positional, keyword, default, `*args`, and `**kwargs` arguments, and return values with `return`.Key concepts:
- Functions are first-class objects (assignable, passable, storable)
- Scope follows LEGB rule: Local, Enclosing, Global, Built-in
- `return` without a value (or no return) gives `None`
- Type hints are optional: `def f(x: int) -> str:`
- Closures capture variables from enclosing scope; use `nonlocal` to modify them
5. 5. What is a data structure ?
Show answer
Solution: Data structure refers to the way data is organized and manipulated. It seeks to find ways to make data access more efficient. When dealing with the data structure, we not only focus on one piece of data but the different set of data and how they can relate to one another in an organized manner.6. 1. What are the key features of Python?
Show answer
Key Python features:- **Interpreted** with dynamic typing — no compilation step needed
- **Multi-paradigm**: supports OOP, functional, and procedural styles
- **Rich standard library** ("batteries included") and massive ecosystem (PyPI)
- **Readability-focused** syntax with significant whitespace
- **Cross-platform**: runs on Linux, macOS, Windows
- **Memory management**: automatic garbage collection with reference counting
- **Extensible**: can integrate with C/C++ libraries