Avito interview questions & answers

8 real Avito interview questions with full model answers — Coding. Drawn from the same verified bank ChannelPulse drills from (8 Avito questions in total).

CodingEasyAvitoSoftware Engineer

1. Merge Sorted Array (LeetCode)

Model answer

The task

Combine two already sorted arrays into one sorted array, placing the result in the first array. The first array has enough spare capacity to hold all elements from both arrays.

Key idea

Fill the first array from right to left. Comparing the largest remaining elements avoids overwriting values in the first array that have not yet been processed.

Approach

  1. Set pointers to the last valid elements of both arrays.
  2. Set a write pointer to the last slot in the first array.
  3. While the second array still has elements, compare the values at the two read pointers.
  4. Write the larger value at the write pointer, then move the corresponding read pointer and the write pointer left.
  5. Any remaining elements from the second array are copied into the first. Remaining elements from the first are already in place.
class Solution:
    def merge(self, nums1: list[int], m: int, nums2: list[int], n: int) -> None:
        """Merge nums2 into nums1 in-place, keeping nums1 sorted."""
        i = m - 1          # Last initialized element in nums1
        j = n - 1          # Last element in nums2
        write = m + n - 1  # Last available position in nums1

        # Fill from the back so unread nums1 elements are not overwritten.
        while j >= 0:
            if i >= 0 and nums1[i] > nums2[j]:
                nums1[write] = nums1[i]
                i -= 1
            else:
                nums1[write] = nums2[j]
                j -= 1
            write -= 1

Complexity:

  • Time: O(m + n), since each element is considered at most once.
  • Space: O(1), because the merge modifies the first array directly.

Common follow-ups

  • What if the arrays are sorted in descending order? Reverse the comparison or adapt the traversal direction.
  • What if the result must go into a separate array? Use two forward pointers and allocate O(m + n) extra space.
  • What if either array is empty? The loop naturally handles it; if the second is empty, the first is already complete.
  • Why merge from the end? Writing from the front could overwrite unprocessed elements in the first array.
CodingEasyAvitoSoftware Engineer

2. Maximum Depth of Binary Tree (LeetCode)

Model answer

The task

Given the root of a binary tree, return the number of nodes on its longest path from the root to a leaf. An empty tree has depth zero.

Key idea

For any non-empty node, its deepest path goes through either its left or right child. Its depth is one plus the larger depth of those subtrees.

Approach

  1. If the current node is None, return zero.
  2. Recursively find the depth of the left subtree.
  3. Recursively find the depth of the right subtree.
  4. Return one plus the larger result.
# Definition for a binary tree node:
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        # An empty subtree contributes no nodes to the depth.
        if root is None:
            return 0

        left_depth = self.maxDepth(root.left)
        right_depth = self.maxDepth(root.right)

        # Count this node, then take the deeper subtree.
        return 1 + max(left_depth, right_depth)

Complexity:

  • Time: O(n), where n is the number of nodes; each node is visited once.
  • Space: O(h), where h is the tree height due to the recursive call stack. In the worst case, h is n.

Common follow-ups

  • How can this be solved iteratively? Use a queue for breadth-first search and count the levels processed.
  • What if the tree is very skewed and recursion depth is a concern? Use iterative breadth-first search to avoid a deep call stack.
  • How does the solution change for an N-ary tree? Compute the maximum depth among all children, then add one for the current node.
CodingMediumAvitoSoftware Engineer

3. Kth Largest Element in an Array (LeetCode)

Model answer

The task

Find the value that would appear in position k when the array is sorted from largest to smallest. Duplicate values count as separate positions.

Key idea

The answer is the element at index len(nums) - k in ascending order. Quickselect partitions the array around pivots, then continues only in the partition that contains that index.

Approach

  1. Convert k to its target index in ascending order.
  2. Choose a random pivot to reduce the chance of consistently poor partitions.
  3. Partition into values smaller than, equal to, and greater than the pivot.
  4. Narrow the search to the partition containing the target, or return the pivot if the target lies among the equal values.
import random
from typing import List

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        target = len(nums) - k
        left, right = 0, len(nums) - 1

        while left <= right:
            pivot = nums[random.randint(left, right)]

            # Three-way partition:
            # nums[left:lt] < pivot
            # nums[lt:gt + 1] == pivot
            # nums[gt + 1:right + 1] > pivot
            lt, i, gt = left, left, right
            while i <= gt:
                if nums[i] < pivot:
                    nums[lt], nums[i] = nums[i], nums[lt]
                    lt += 1
                    i += 1
                elif nums[i] > pivot:
                    nums[i], nums[gt] = nums[gt], nums[i]
                    gt -= 1
                else:
                    i += 1

            if target < lt:
                right = lt - 1
            elif target > gt:
                left = gt + 1
            else:
                return pivot

        raise ValueError("k must be within the array's valid range")

Complexity:

  • Time: O(n) on average, since each partition discards the portions that cannot contain the answer.
  • Space: O(1) auxiliary space; the partitioning is in place.

Common follow-ups

  • What if worst-case time must be bounded? Use a min-heap of size k for O(n log k) time.
  • How do duplicates affect the result? Each occurrence occupies its own rank; the three-way partition handles equal values together.
  • Can the input remain unchanged? Make a copy before partitioning, at the cost of O(n) extra space.
CodingMediumAvitoSoftware Engineer

4. Sum of Subarray Minimums (LeetCode)

Model answer

The task

Find the sum of the minimum value in every contiguous subarray of arr, returning the result modulo \(10^9+7\).

Key idea

Count how many subarrays have each element as their minimum, then add that element’s contribution. A monotonic stack finds the nearest smaller boundaries in linear time; popping equal values gives duplicate minima a consistent tie-break.

Approach

  1. Scan left to right with a stack of indices whose values are increasing.
  2. When the current value is less than or equal to the stack top, pop that index. The current index is its next less-than-or-equal boundary.
  3. The new stack top, if present, is its previous strictly smaller boundary.
  4. Multiply the number of choices for the left and right endpoints by the popped value, and add that contribution.
  5. Use a final sentinel step to process every remaining index, then take the sum modulo \(10^9+7\).
from typing import List

class Solution:
    def sumSubarrayMins(self, arr: List[int]) -> int:
        mod = 10**9 + 7
        n = len(arr)
        stack = []
        total = 0

        # The final iteration acts as a sentinel to flush the stack.
        for right in range(n + 1):
            while stack and (
                right == n or arr[stack[-1]] >= arr[right]
            ):
                index = stack.pop()
                left = stack[-1] if stack else -1

                # Choose a start after left and an end before right.
                count = (index - left) * (right - index)
                total += arr[index] * count

            if right < n:
                stack.append(right)

        return total % mod

Complexity:

  • Time: O(n), since each index is pushed and popped at most once.
  • Space: O(n) for the monotonic stack.

Common follow-ups

  • Why pop on equality? It assigns subarrays with tied minima to one occurrence consistently, preventing double counting.
  • What if the exact sum is needed? Return total without applying the modulus.
  • What if we need the minimum of each fixed-size sliding window? Use a monotonic deque, removing indices that leave the window or are dominated by a newer value.
CodingMediumAvitoSoftware Engineer

5. Generate Parentheses (LeetCode)

Model answer

The task

Given a nonnegative number of pairs, return every string of that many opening and closing parentheses that is correctly balanced.

Key idea

Build each string one character at a time. Add an opening parenthesis only while fewer than n have been used, and add a closing parenthesis only when it will not outnumber the openings already used.

Approach

  1. Track how many opening and closing parentheses have been added, plus the current string.
  2. If the string has length 2 * n, save it.
  3. Recurse with an opening parenthesis when fewer than n openings have been used.
  4. Recurse with a closing parenthesis when fewer closings have been used than openings.
  5. Start with an empty string and zero counts.
from typing import List

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        results: List[str] = []
        current: list[str] = []

        def backtrack(open_count: int, close_count: int) -> None:
            if len(current) == 2 * n:
                results.append("".join(current))
                return

            if open_count < n:
                current.append("(")
                backtrack(open_count + 1, close_count)
                current.pop()

            if close_count < open_count:
                current.append(")")
                backtrack(open_count, close_count + 1)
                current.pop()

        backtrack(0, 0)
        return results

Complexity:

  • Time: O(Cₙ · n), where Cₙ is the number of valid strings; each is assembled in O(n) time.
  • Space: O(n) auxiliary space for the recursion and current string, excluding the returned results.

Common follow-ups

  • How can you count the results without generating them? Use the Catalan number formula, Cₙ = binomial(2n, n) / (n + 1).
  • What happens when n is zero? The algorithm returns a list containing the empty string.
  • How would you generate strings with multiple bracket types? Track each type’s balance and ensure closing brackets match the most recent unmatched opening bracket.
CodingMediumAvitoSoftware Engineer

6. Top K Frequent Elements (LeetCode)

Model answer

The task

Given an integer array and a value k, return the k values that occur most often. Their order does not matter.

Key idea

Count each value’s occurrences, then group values by frequency. Since no frequency can exceed the array length, scan these groups from highest frequency down until k values are collected.

Approach

  1. Build a frequency map from each value to its count.
  2. Create buckets indexed by frequency.
  3. Put each distinct value into the bucket for its count.
  4. Scan buckets from highest to lowest, collecting values until there are k.
from collections import defaultdict
from typing import List

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        # Count occurrences of each value.
        frequency = defaultdict(int)
        for value in nums:
            frequency[value] += 1

        # Bucket each value by its frequency.
        buckets = [[] for _ in range(len(nums) + 1)]
        for value, count in frequency.items():
            buckets[count].append(value)

        # Collect values from most frequent to least frequent.
        result = []
        for count in range(len(nums), 0, -1):
            for value in buckets[count]:
                result.append(value)
                if len(result) == k:
                    return result

        return result

Complexity:

  • Time: O(n), where n is the array length; counting and scanning the buckets take linear time.
  • Space: O(n), for the frequency map and buckets.

Common follow-ups

  • How would you solve it with a heap? Keep a size-k heap of distinct values, giving O(n + m log k) time, where m is the number of distinct values.
  • What if results must be ordered by frequency? Sort the selected values by their counts, or collect them in descending bucket order.
  • What if the data arrives as a stream? Maintain approximate counts with a streaming frequency sketch, or use a bounded candidate structure when exact counts are not feasible.
CodingMediumAvitoSoftware Engineer

7. Product of Array Except Self (LeetCode)

Model answer

The task

Given an integer array, return an array where each position contains the product of every input value except the one at that same position. Do so without division.

Key idea

For each position, multiply the product of all values to its left by the product of all values to its right. Store left products in the result, then accumulate right products in a second pass.

Approach

  1. Create a result array initialized to 1.
  2. Scan from left to right, storing the product of values seen before each position.
  3. Scan from right to left, multiplying each result by the product of values after that position.
  4. Update the running right-side product after processing each position.
from typing import List

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n = len(nums)
        result = [1] * n

        # Store the product of all elements to the left of each index.
        left_product = 1
        for i in range(n):
            result[i] = left_product
            left_product *= nums[i]

        # Multiply by the product of all elements to the right.
        right_product = 1
        for i in range(n - 1, -1, -1):
            result[i] *= right_product
            right_product *= nums[i]

        return result

Complexity:

  • Time: O(n), with two passes over the array.
  • Space: O(1) auxiliary space, excluding the result array.

Common follow-ups

  • What if the array contains zeros? The same method works without special cases.
  • Can this be done with division? Division requires careful handling of zeros and may be disallowed; the two-pass method avoids it.
  • Can the result be computed in place? The output array already stores the left products, then is updated with right products.
CodingMediumAvitoSoftware Engineer

8. Group Anagrams (LeetCode)

Model answer

The task

Partition the input strings into groups so that strings in the same group contain the same characters with the same frequencies. The order of the groups does not matter.

Key idea

Sort the characters of each string to create a canonical key. Anagrams produce the same key, so a hash table can collect them together.

Approach

  1. Create a mapping from canonical keys to lists of original strings.
  2. For each string, sort its characters and use the result as its key.
  3. Append the string to the list for that key.
  4. Return all grouped lists.
from collections import defaultdict
from typing import List

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groups = defaultdict(list)

        for word in strs:
            # Anagrams have identical sorted-character representations.
            key = "".join(sorted(word))
            groups[key].append(word)

        return list(groups.values())

Complexity:

  • Time: O(n · k log k), where n is the number of strings and k is the maximum string length.
  • Space: O(n · k) to store the grouped strings and their keys.

Common follow-ups

  • Can this be faster for a fixed alphabet? Use a character-frequency tuple as the key, computing it in O(k) per string.
  • Does this work with uppercase letters or Unicode? Yes; sorting characters works for any Python strings.
  • Can groups be returned in a deterministic order? Sort the groups, or their keys, before returning them.
  • What if memory is limited? Consider processing input in batches or grouping externally by canonical key.

Practice these out loud, don't memorise them

Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.

Get ChannelPulse Browse all questions