Interview Q&A / Python

INTERVIEW Q&A · 81 QUESTIONS

Python interview questions

Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.

  1. Write a function that reverses a string in Python.

    The shortest way is slicing with a negative step: s[::-1]. You can also use "".join(reversed(s)). Both build a new string in O(n) time, since strings cannot be changed in place.

    BeginnerQuick answerCoding1 min read
  2. Write a function to check whether a string is a palindrome, ignoring case and non-letters.

    Clean the string by keeping only letters and digits in lowercase, then compare it with its reverse. This runs in O(n) time. A two-pointer version avoids the extra reversed copy.

    BeginnerQuick answerCoding1 min read
  3. Write a function to check whether two strings are anagrams of each other.

    Two strings are anagrams if they contain the same characters with the same counts. Compare Counter(a) with Counter(b) in O(n) time, or compare sorted(a) with sorted(b) in O(n log n) time.

    BeginnerQuick answerCoding1 min read
  4. Write a function to flatten a list of lists into a single list.

    For one level of nesting, use a nested comprehension: [x for row in rows for x in row]. For arbitrary depth, use recursion and check isinstance(item, list). The flat version is O(n) in the number of elements.

    BeginnerQuick answerCoding1 min read
  5. Write a function to remove duplicates from a list while keeping the original order.

    Walk through the list, keep a set of items already seen, and add an item to the result only if it is not in the set. This is O(n) time. Using set(lst) alone is fast but loses the order.

    BeginnerQuick answerCoding1 min read
  6. Write a generator that yields the first n Fibonacci numbers.

    Keep two variables a and b, yield a, then update them with a, b = b, a + b, repeating n times. The generator produces one value at a time, uses O(1) memory and does O(n) additions in total.

    BeginnerQuick answerCoding1 min read
  7. Write a class that implements the iterator protocol to count down from n to 1.

    Define __iter__ returning self and __next__ returning the next value, raising StopIteration when the countdown ends. Store the current position on the instance. Each next call is O(1) and the class uses O(1) space.

    IntermediateQuick answerCoding1 min read
  8. Write a function to transpose a matrix (swap its rows and columns).

    Use zip(*matrix) and convert each tuple to a list, or use a nested comprehension indexing matrix[r][c]. The first row becomes the first column. The time is O(rows x cols).

    IntermediateQuick answerCoding1 min read