Five Brain-Bending Python Interview Challenges: Hard MCQ Quiz Quiz

  1. Reverse only if all characters are unique

    Which one-line Python expression reverses a string s only when all of its characters are unique, without using slicing [::-1] or reversed(), for example producing 'cba' from s='abc' but leaving s='abca' unchanged?

    1. ''.join(s[i] for i in range(len(s)-1, -1, -1)) if len(s) == len(set(s)) else s
    2. ''.join(reversed(s)) if len(s) == len(set(s)) else s
    3. s[::-1] if len(set(s)) == len(s) else s
    4. ''.join(s[i] for i in range(len(s))) if len(set(s)) == len(s) else s
    5. s if len(set(s)) == len(s) else ''.join(s[i] for i in range(len(s)-1, -1, -1))
  2. Second-largest in one pass without sorting

    Given a list nums and sentinels largest = second = float('-inf'), which in-loop update logic correctly computes a distinct second-largest value in a single pass without using sort or sorted, even when nums contains duplicates (e.g., nums=[5, 1, 5, 3])?

    1. if x u003E largest: second, largest = largest, x; elif x u003C largest and x u003E second: second = x
    2. if x u003E= largest: second, largest = largest, x; elif x u003E second: second = x
    3. if x u003E largest: largest, second = x, second; elif x u003E second: second = x
    4. if x u003E largest: second = x; largest = x
    5. if x u003E largest and x u003E second: second = x; largest = x
  3. Flatten a shallow nested list without recursion in one line

    Which one-line Python expression flattens a list like lst = [1, [2, 3], [4, 5], 6] into [1, 2, 3, 4, 5, 6] without using recursion or additional imports?

    1. [y for x in lst for y in (x if isinstance(x, list) else [x])]
    2. [item for sub in lst for item in sub]
    3. list(sum(lst))
    4. list(chain.from_iterable(lst))
    5. flatten(lst)
  4. Understanding reverse indices with range

    For a string s of length 4, what sequence of indices does range(len(s)-1, -1, -1) generate, which is commonly used to traverse s in reverse without slicing?

    1. [3, 2, 1, 0]
    2. [4, 3, 2, 1]
    3. [3, 2, 1]
    4. [0, 1, 2, 3]
    5. [-1, -2, -3, -4]
  5. Applying reverse-if-unique to a non-unique string

    When evaluating the expression ''.join(s[i] for i in range(len(s)-1, -1, -1)) if len(s) == len(set(s)) else s on s = 'abca', what string is returned?

    1. abca
    2. acba
    3. aabc
    4. a c b a