LearnFrenzy
Sign in Take a free test

Python Programming interview · Set 17 of 19

Python Coding Interview Questions – Part 1 (Basics)

  • 7 follow-up questions
  • 4 key points
  • Code examples
Test yourself

The classic placement programs

These problems are simple on purpose. Interviewers judge clarity, edge cases and whether you can state the complexity — so write clean code and talk through it.

  • NumbersReverse, prime, Armstrong and missing number.
  • SequencesFibonacci, factorial and FizzBuzz.
  • ArraysSecond largest in one pass.

These are the programs asked again and again in campus placements and first-round coding tests. Each solution is the clean, Pythonic version with its time complexity — and where useful, the follow-up an interviewer is likely to ask next.

1. Reverse a number and check if it is a palindrome.

Use arithmetic to show you understand digits, or string slicing for the Pythonic one-liner. Mention negative numbers.

def reverse_number(n: int) -> int:
    sign, n = (-1, -n) if n < 0 else (1, n)
    rev = 0
    while n:
        rev = rev * 10 + n % 10
        n //= 10
    return sign * rev

print(reverse_number(1234))          # 4321
print(str(1221) == str(1221)[::-1])  # palindrome check: True

2. Check whether a number is prime efficiently.

Only test divisors up to the square root, skip even numbers after 2. Time O(√n). For many numbers, use the Sieve of Eratosthenes.

def is_prime(n: int) -> bool:
    if n < 2:
        return False
    if n % 2 == 0:
        return n == 2
    d = 3
    while d * d <= n:
        if n % d == 0:
            return False
        d += 2
    return True

def primes_up_to(limit: int) -> list[int]:     # sieve, O(n log log n)
    sieve = [True] * (limit + 1)
    sieve[0:2] = [False, False]
    for i in range(2, int(limit ** 0.5) + 1):
        if sieve[i]:
            sieve[i * i::i] = [False] * len(range(i * i, limit + 1, i))
    return [i for i, ok in enumerate(sieve) if ok]

3. Generate the Fibonacci series.

The iterative version is O(n) time and O(1) space. A generator lets callers take as many terms as they need. Mention that naive recursion is O(2ⁿ).

def fibonacci(n: int) -> list[int]:
    a, b, out = 0, 1, []
    for _ in range(n):
        out.append(a)
        a, b = b, a + b
    return out

print(fibonacci(10))   # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

4. Find the factorial iteratively and recursively.

Both are O(n). Python integers have arbitrary precision, so large factorials do not overflow — but deep recursion hits the recursion limit, so prefer the loop (or math.factorial).

def factorial(n: int) -> int:
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

def factorial_rec(n: int) -> int:
    return 1 if n <= 1 else n * factorial_rec(n - 1)

print(factorial(20))   # 2432902008176640000

5. Check for an Armstrong number.

A number equal to the sum of its digits each raised to the number of digits (153 = 1³ + 5³ + 3³).

def is_armstrong(n: int) -> bool:
    digits = str(n)
    power = len(digits)
    return n == sum(int(d) ** power for d in digits)

print([n for n in range(1, 1000) if is_armstrong(n)])
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407]

6. Write FizzBuzz — and make it easy to extend.

The basic version is about getting conditions in the right order. A rule table shows design sense: adding “Jazz” for 7 is one line.

RULES = [(3, "Fizz"), (5, "Buzz")]

def fizzbuzz(n: int) -> list[str]:
    out = []
    for i in range(1, n + 1):
        word = "".join(text for d, text in RULES if i % d == 0)
        out.append(word or str(i))
    return out

print(fizzbuzz(15)[-1])   # FizzBuzz

7. Find the second largest number without sorting.

One pass with two variables — O(n). Handle duplicates and lists with fewer than two distinct values.

def second_largest(nums: list[int]) -> int | None:
    first = second = None
    for x in nums:
        if first is None or x > first:
            first, second = x, first
        elif x != first and (second is None or x > second):
            second = x
    return second

print(second_largest([10, 40, 40, 25, 30]))   # 30

8. Find the missing number from 1 to n.

The expected sum minus the actual sum gives the missing number in O(n) time and O(1) space. XOR is an overflow-free alternative in other languages.

def missing_number(nums: list[int], n: int) -> int:
    return n * (n + 1) // 2 - sum(nums)

print(missing_number([1, 2, 4, 5, 6], 6))   # 3

Remember

Key points

  • Divisors up to √n

    Makes prime checks O(√n).

  • Iterate, do not recurse deeply

    Python has a recursion limit.

  • Sum formula for missing numbers

    O(n) time, O(1) space.

  • State complexity every time

    Time and space, out loud.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 Swap two numbers without a third variable. Basic

    In Python: a, b = b, a. The arithmetic trick (a = a + b; b = a - b; a = a - b) is for languages without tuple unpacking.

  2. 2 Count vowels in a string. Basic

    sum(ch in "aeiou" for ch in text.lower()).

  3. 3 Find the GCD and LCM of two numbers. Basic

    Euclid's algorithm, or math.gcd and math.lcm.

    def gcd(a, b):
        while b:
            a, b = b, a % b
        return a
    
    def lcm(a, b):
        return a * b // gcd(a, b)
  4. 4 Check whether a year is a leap year. Basic

    Divisible by 4 and not by 100, unless also divisible by 400: y % 4 == 0 and (y % 100 != 0 or y % 400 == 0).

  5. 5 Sum the digits of a number until one digit remains. Intermediate

    Loop, or use the digital-root formula 0 if n == 0 else 1 + (n - 1) % 9.

  6. 6 Print a right-angled star pattern of n rows. Basic

    String multiplication keeps it short.

    for i in range(1, 6):
        print("*" * i)
  7. 7 Convert a decimal number to binary without bin(). Intermediate

    Repeatedly divide by 2 and collect remainders in reverse.

    def to_binary(n):
        if n == 0:
            return "0"
        bits = []
        while n:
            bits.append(str(n % 2))
            n //= 2
        return "".join(reversed(bits))

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links