Ozon interview questions & answers

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

CodingEasyOzonSoftware Engineer

1. Two Sum (LeetCode)

Model answer

The task

Given a list of integers and a target, return the indices of two distinct elements whose values add up to the target. The usual version guarantees a valid pair.

Key idea

As we scan the list, store each value’s index in a hash table. For the current value, check whether its needed complement has already appeared; this finds a pair in one pass.

Approach

  1. Create a dictionary mapping previously seen values to their indices.
  2. For each element, compute the complement needed to reach the target.
  3. If that complement is in the dictionary, return its stored index and the current index.
  4. Otherwise, store the current value and index, then continue.
from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # Map each value already visited to its index.
        seen = {}

        for index, value in enumerate(nums):
            complement = target - value

            # A match must come from an earlier, distinct element.
            if complement in seen:
                return [seen[complement], index]

            seen[value] = index

        # The standard problem guarantees a solution.
        raise ValueError("No two elements sum to the target")

Complexity:

  • Time: O(n), where n is the number of elements; each lookup and insertion is O(1) on average.
  • Space: O(n), for the dictionary of values seen so far.

Common follow-ups

  • What if there may be multiple valid pairs? Return the first pair found, or keep searching and collect pairs according to the required output rules.
  • What if the input is sorted? Use two pointers from opposite ends for O(1) extra space; preserve original indices if those are required.
  • What if values repeat? The dictionary stores indices, and checking before insertion ensures the current element is not paired with itself.
CodingEasyOzonSoftware Engineer

2. Valid Parentheses (LeetCode)

Model answer

The task

Determine whether a string of opening and closing round, square, and curly brackets is correctly nested and matched. Return a boolean.

Key idea

A closing bracket must match the most recent unmatched opening bracket. A stack captures that order: push openings, and check each closing bracket against the stack’s top.

Approach

  1. Return False if the string has odd length.
  2. Map each closing bracket to its matching opening bracket.
  3. Scan the string from left to right.
  4. Push opening brackets onto the stack.
  5. For a closing bracket, return False if the stack is empty or its top does not match; otherwise pop.
  6. Return True only if the stack is empty after the scan.
class Solution:
    def isValid(self, s: str) -> bool:
        pairs = {")": "(", "]": "[", "}": "{"}
        openings = set(pairs.values())
        stack = []

        for char in s:
            if char in openings:
                stack.append(char)
            else:
                # A closing bracket must match the latest unmatched opening.
                if not stack or stack[-1] != pairs.get(char):
                    return False
                stack.pop()

        # Unmatched opening brackets make the sequence invalid.
        return not stack

Complexity:

  • Time: O(n), where n is the string length; each character is processed once.
  • Space: O(n) in the worst case, when all characters are opening brackets.

Common follow-ups

  • How would you support additional bracket types? Add their matching pairs to the map.
  • Can you stop early? Yes; return False as soon as a closing bracket mismatches or has no opening bracket.
  • What if the input includes non-bracket characters? Define how to handle them, then either ignore them or reject them during the scan.
CodingEasyOzonSoftware Engineer

3. Monotonic Array (LeetCode)

Model answer

The task

Determine whether an integer array is monotonic: its values must either never decrease or never increase as you move from left to right. Equal adjacent values are allowed.

Key idea

Track whether the array could still be nondecreasing and whether it could still be nonincreasing. A pair that violates one direction rules out that possibility; if either direction remains possible, the array is monotonic.

Approach

  1. Start with both direction flags set to True.
  2. Compare each value with its predecessor.
  3. If a value is smaller, the array cannot be nondecreasing.
  4. If a value is larger, the array cannot be nonincreasing.
  5. Return whether either flag remains true. Arrays with fewer than two values are monotonic by this check.
from typing import List

class Solution:
    def isMonotonic(self, nums: List[int]) -> bool:
        nondecreasing = True
        nonincreasing = True

        for i in range(1, len(nums)):
            if nums[i] < nums[i - 1]:
                nondecreasing = False
            if nums[i] > nums[i - 1]:
                nonincreasing = False

        return nondecreasing or nonincreasing

Complexity:

  • Time: O(n), where n is the length of the array; each adjacent pair is checked once.
  • Space: O(1), using only two flags.

Common follow-ups

  • Can you return which direction it is monotonic? Return the surviving direction flag, handling arrays with all equal values as both directions.
  • What if the data arrives as a stream? Keep the previous value and the two flags, updating them for each new value.
  • How do you handle floating-point values? Use the same comparisons, but decide whether near-equal values should count as equal under a tolerance.
CodingEasyOzonSoftware Engineer

4. Squares of a Sorted Array (LeetCode)

Model answer

The task

Given an array sorted in nondecreasing order, return a new array containing the square of each value, also sorted in nondecreasing order.

Key idea

Squaring can make negative values large, so the largest square must come from one of the two ends of the input. Compare the absolute values at both ends and fill the result from right to left.

Approach

  1. Set pointers at the first and last elements.
  2. Allocate a result array of the same length.
  3. Compare the absolute values at the pointers.
  4. Place the larger square at the current result position, then move the corresponding pointer inward.
  5. Continue until every position has been filled.
class Solution:
    def sortedSquares(self, nums: list[int]) -> list[int]:
        left, right = 0, len(nums) - 1
        result = [0] * len(nums)
        write = len(nums) - 1

        while left <= right:
            if abs(nums[left]) > abs(nums[right]):
                value = nums[left]
                left += 1
            else:
                value = nums[right]
                right -= 1

            result[write] = value * value
            write -= 1

        return result

Complexity:

  • Time: O(n), since each input element is processed once.
  • Space: O(n), for the returned array.

Common follow-ups

  • Can this be done without allocating a result array? Not while returning a separate sorted array in the general case; the output itself requires O(n) space.
  • What if the input is not sorted? Sort it first, which takes O(n log n), then use the two-pointer method.
  • How do duplicates affect the algorithm? They need no special handling; equal absolute values produce equal squares.
CodingEasyOzonSoftware Engineer

5. Best Time to Buy and Sell Stock (LeetCode)

Model answer

The task

Given daily stock prices, find the greatest profit possible from one buy followed by one later sale. If no sale would make money, return zero.

Key idea

As we scan the prices, keep the lowest price seen so far. Treat each current price as a possible sale and update the best profit using the difference from that minimum.

Approach

  1. Initialize the minimum price to a value larger than any price and the best profit to zero.
  2. Visit each price in order.
  3. Update the minimum price with the current price.
  4. Check the profit from selling today and update the best profit.
  5. Return the best profit.
class Solution:
    def maxProfit(self, prices: list[int]) -> int:
        min_price = float("inf")
        best_profit = 0

        for price in prices:
            # The current price can be a new best day to buy.
            min_price = min(min_price, price)

            # Or it can be the day to sell after the cheapest earlier buy.
            best_profit = max(best_profit, price - min_price)

        return best_profit

Complexity:

  • Time: O(n), where n is the number of prices; each is processed once.
  • Space: O(1), since only a few variables are stored.

Common follow-ups

  • What if multiple buy-and-sell transactions are allowed? Sum the gains from every adjacent price increase.
  • What if a transaction fee is charged? Track the best holding and non-holding profits, incorporating the fee when selling.
  • What if at most k transactions are allowed? Use dynamic programming over the number of completed transactions and whether a share is currently held.
CodingEasyOzonSoftware Engineer

6. Valid Anagram (LeetCode)

Model answer

The task

Determine whether two strings contain the same characters with the same frequencies, regardless of order.

Key idea

Anagrams have identical character counts. Count the characters in each string and compare the resulting frequency maps.

Approach

  1. If the strings have different lengths, return False.
  2. Build a frequency map for each string.
  3. Return whether the maps are equal.
from collections import Counter

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # Different lengths cannot have matching character counts.
        if len(s) != len(t):
            return False

        # Anagrams have exactly the same character frequencies.
        return Counter(s) == Counter(t)

Complexity:

  • Time: O(n), where n is the length of either string; counting and comparison are linear.
  • Space: O(k), where k is the number of distinct characters stored in the frequency maps.

Common follow-ups

  • Can you do this without two maps? Update one frequency map using s, then decrement counts using t; verify all counts return to zero.
  • What if the input is guaranteed to contain only lowercase English letters? Use a fixed-size array of 26 counters instead of maps.
  • What if sorting is allowed? Sort both strings and compare them; this takes O(n log n) time.
CodingMediumOzonSoftware Engineer

7. Decode String (LeetCode)

Model answer

The task

Decode a string where a number before brackets indicates how many times to repeat the bracketed section. Sections may be nested.

Key idea

Parse the input into a compact tree of literal fragments and repeat nodes instead of expanding nested sections immediately. Then traverse that tree to produce the decoded string, avoiding repeated copying of large intermediate strings.

Approach

  1. Scan the input, accumulating each repetition count.
  2. On an opening bracket, save the current fragment list and count, then start a new list.
  3. On a closing bracket, wrap the current list in a repeat node and add it to its parent.
  4. Traverse the resulting structure with an explicit stack, yielding literal fragments as they are needed.
  5. Join the yielded fragments into the result.
class Solution:
    def decodeString(self, s: str) -> str:
        # Each repeat node is a (count, fragments) tuple.
        current = []
        stack = []
        count = 0

        for char in s:
            if "0" <= char <= "9":
                count = count * 10 + int(char)
            elif char == "[":
                stack.append((current, count))
                current = []
                count = 0
            elif char == "]":
                parent, repeat = stack.pop()
                # Omit zero repetitions so traversal skips empty sections.
                if repeat:
                    parent.append((repeat, current))
                current = parent
            else:
                current.append(char)

        def fragments():
            # Frames contain a fragment list, its next index, and
            # how many times to traverse that list.
            frames = [[current, 0, 1]]

            while frames:
                parts, index, remaining = frames[-1]

                if index == len(parts):
                    remaining -= 1
                    if remaining == 0:
                        frames.pop()
                    else:
                        frames[-1][1] = 0
                        frames[-1][2] = remaining
                    continue

                node = parts[index]
                frames[-1][1] += 1

                if isinstance(node, str):
                    yield node
                else:
                    repeat, nested = node
                    frames.append([nested, 0, repeat])

        return "".join(fragments())

Complexity:

  • Time: O(n + m), where n is the encoded length and m is the decoded length.
  • Space: O(n + m) for the parsed structure and returned string.

Common follow-ups

  • How would you handle malformed input? Validate bracket balance and ensure each opening bracket has a preceding count.
  • How could this support streaming output? Yield decoded fragments to a consumer instead of joining them into one string.
  • What if the grammar adds escaping or other operators? Extend the parser with explicit rules and represent each operation as a distinct node.
CodingMediumOzonSoftware Engineer

8. Merge Intervals (LeetCode)

Model answer

The task

Given a collection of intervals, combine every pair that overlaps and return the resulting non-overlapping intervals. The result should be ordered by starting point.

Key idea

Sort intervals by their start. Then scan once, keeping the most recently merged interval; each next interval either extends it or starts a new one.

Approach

  1. Sort the intervals by their start value.
  2. Initialize the result with the first interval, if any.
  3. For each remaining interval, compare its start with the end of the last result interval.
  4. If they overlap, update that end to the larger of the two ends.
  5. Otherwise, append the interval as a new result.
from typing import List

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        if not intervals:
            return []

        intervals.sort(key=lambda interval: interval[0])
        merged = [intervals[0]]

        for start, end in intervals[1:]:
            # The intervals overlap, so extend the last merged interval.
            if start <= merged[-1][1]:
                merged[-1][1] = max(merged[-1][1], end)
            else:
                # No overlap: this interval begins a new merged range.
                merged.append([start, end])

        return merged

Complexity: Time: O(n log n), dominated by sorting n intervals.

Complexity: Space: O(n) for the merged result; sorting may also use up to O(n) space.

Common follow-ups

  • What if intervals that only touch at an endpoint should remain separate? Use start < merged[-1][1] as the overlap test.
  • How would you merge intervals as they arrive in sorted order? Skip sorting and apply the same scan, processing each interval once.
  • What if intervals are inserted one at a time into an already merged collection? Use binary search to find the insertion point, then merge neighboring overlaps.
CodingMediumOzonSoftware Engineer

9. Min Stack (LeetCode)

Model answer

The task

Design a stack that supports pushing and removing values, inspecting the top value, and retrieving the minimum value currently stored. Each operation should take constant time.

Key idea

Alongside each value, store the minimum seen at that point in the stack. The top entry then contains enough information to answer a minimum query without scanning the stack.

Approach

  1. Keep a list of (value, minimum_so_far) pairs.
  2. On push, compare the new value with the current minimum and store the smaller one.
  3. On pop, remove the top pair.
  4. Return the value or minimum from the top pair for top and getMin.
class MinStack:
    def __init__(self):
        # Each entry is (value, minimum among entries up to this one).
        self.stack = []

    def push(self, val: int) -> None:
        current_min = val
        if self.stack:
            current_min = min(val, self.stack[-1][1])
        self.stack.append((val, current_min))

    def pop(self) -> None:
        self.stack.pop()

    def top(self) -> int:
        return self.stack[-1][0]

    def getMin(self) -> int:
        return self.stack[-1][1]

Complexity:

  • Time: O(1) per operation; each method accesses or updates only the top entry.
  • Space: O(n); each stack entry stores its value and the minimum so far.

Common follow-ups

  • Can you reduce the extra space? Store only values and keep a second stack of minimums, pushing a minimum when it is no greater than the current one.
  • How should duplicate minimums be handled? Track duplicates in the minimum stack too, so popping one leaves the other available.
  • What if the stack can be empty when queried? Define the API’s empty-stack behavior, such as raising an exception or returning a sentinel.
CodingMediumOzonSoftware Engineer

10. Department Highest Salary (LeetCode)

Model answer

The task

Return each department’s highest-paid employee or employees, including their department name, employee name, and salary. If multiple employees tie for the highest salary in a department, include them all.

Key idea

Find the maximum salary for each department, then join those results back to the employee and department tables. Joining on both department and salary preserves every employee tied at the maximum.

Approach

  1. Group employees by department and calculate each department’s maximum salary.
  2. Match employees whose salary equals their department’s maximum.
  3. Join the matching employees to their department names.
  4. Select the required columns.
-- Find each department's maximum salary, then return every employee
-- whose salary matches that maximum.
SELECT
    d.name AS Department,
    e.name AS Employee,
    e.salary AS Salary
FROM Employee AS e
JOIN Department AS d
    ON d.id = e.departmentId
JOIN (
    SELECT
        departmentId,
        MAX(salary) AS max_salary
    FROM Employee
    GROUP BY departmentId
) AS highest
    ON highest.departmentId = e.departmentId
   AND highest.max_salary = e.salary;

Complexity:

  • Time: O(n) for aggregating and matching employees, assuming efficient joins.
  • Space: O(d) for the grouped maximum salaries, where d is the number of departments.

Common follow-ups

  • How would you return only one employee per department? Add a tie-breaking rule, such as choosing the lowest employee ID.
  • How can this be written with a window function? Use DENSE_RANK() partitioned by department and ordered by salary descending, then keep rank 1.
  • What index could help? An index on (departmentId, salary) can help with grouping and matching.
CodingMediumOzonSoftware Engineer

11. Longest Substring Without Repeating Characters (LeetCode)

Model answer

The task

Find the length of the longest contiguous section of a string in which every character appears at most once.

Key idea

Maintain a sliding window with no repeated characters. When a character repeats within the window, move the left edge just past its previous occurrence.

Approach

  1. Track each character’s most recent index in a dictionary.
  2. Keep left as the window’s starting index and best as its longest length so far.
  3. For each character, move left forward if its previous occurrence is inside the current window.
  4. Record the character’s current index and update best using the window length.
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        last_seen = {}
        left = 0
        best = 0

        for right, char in enumerate(s):
            # Skip past a repeated character if it is in the current window.
            if char in last_seen and last_seen[char] >= left:
                left = last_seen[char] + 1

            last_seen[char] = right
            best = max(best, right - left + 1)

        return best

Complexity:

  • Time: O(n), because each character is processed once.
  • Space: O(k), where k is the number of distinct characters encountered.

Common follow-ups

  • Return the substring itself: store the best window’s start and end indices when updating best.
  • Handle a stream of characters: keep the same window state and process each arriving character incrementally.
  • Use a fixed-size character set: replace the dictionary with an array of last-seen indices.
CodingHardOzonSoftware Engineer

12. Department Top Three Salaries (LeetCode)

Model answer

The task

Return employees whose salary is among the three highest distinct salaries in their department. Include all employees tied at one of those salary levels.

Key idea

Use DENSE_RANK within each department, ordering salaries from highest to lowest. Unlike ROW_NUMBER, it gives equal salaries the same rank and does not skip ranks after ties.

Approach

  1. Rank employees separately within each department by descending salary.
  2. Use DENSE_RANK so each distinct salary level gets one rank.
  3. Keep rows with rank at most three.
  4. Join to the department table to return department names.
WITH ranked_employees AS (
    SELECT
        e.id,
        e.name,
        e.salary,
        e.departmentId,
        DENSE_RANK() OVER (
            PARTITION BY e.departmentId
            ORDER BY e.salary DESC
        ) AS salary_rank
    FROM Employee AS e
)
SELECT
    d.name AS Department,
    r.name AS Employee,
    r.salary AS Salary
FROM ranked_employees AS r
JOIN Department AS d
    ON d.id = r.departmentId
WHERE r.salary_rank <= 3;

Complexity:

  • Time: O(n log n), for ordering employees within departments.
  • Space: O(n), for the ranked rows and window-function processing.

Common follow-ups

  • Return the top K distinct salary levels: Replace 3 with a parameter K.
  • Return exactly three employees per department: Use ROW_NUMBER instead, with a deterministic tie-breaker such as employee ID.
  • Include departments with no employees: Start from Department and use a LEFT JOIN; employee columns will be NULL for empty departments.

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