VK interview questions & answers

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

CodingEasyVKSoftware Engineer

1. Symmetric Tree (LeetCode)

Model answer

The task

Determine whether a binary tree is symmetric around its center: its left and right subtrees must be mirror images.

Key idea

Compare nodes in mirrored pairs. For each pair, their values must match, and their outer children and inner children must also match as mirrored pairs.

Approach

  1. Put the root’s left and right children into a queue as a pair.
  2. Remove a pair; if both nodes are absent, continue. If only one is absent or their values differ, return False.
  3. Add the outer pair of children and the inner pair of children to the queue.
  4. If every pair matches, return True.
from collections import deque
from typing import Optional

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        if root is None:
            return True

        queue = deque([(root.left, root.right)])

        while queue:
            left, right = queue.popleft()

            # Missing nodes must occur in matching positions.
            if left is None or right is None:
                if left is not right:
                    return False
                continue

            if left.val != right.val:
                return False

            # Compare mirrored child positions.
            queue.append((left.left, right.right))
            queue.append((left.right, right.left))

        return True

Complexity:

  • Time: O(n), where n is the number of nodes; each node is checked at most once.
  • Space: O(n) in the worst case for the queue.

Common follow-ups

  • Can this be solved recursively? Yes; define a helper that checks a pair of mirrored nodes and recursively compares their outer and inner children.
  • What if node values are not unique? The method still works because it checks both values and structure.
  • What if the tree is very deep? The iterative queue avoids recursion-depth limits; its memory use depends on the tree’s maximum width.
CodingEasyVKSoftware Engineer

2. 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.
CodingEasyVKSoftware Engineer

3. Valid Palindrome (LeetCode)

Model answer

The task

Determine whether a string reads the same forward and backward after disregarding characters that are not letters or digits and treating uppercase and lowercase as equivalent.

Key idea

Compare characters from both ends, skipping anything that should be ignored. If every remaining pair matches, the string is a palindrome.

Approach

  1. Initialize pointers at the start and end of the string.
  2. Move the left pointer past non-alphanumeric characters.
  3. Move the right pointer past non-alphanumeric characters.
  4. Compare the lowercase forms of the characters at the pointers; return False if they differ.
  5. Move both pointers inward and continue. If they meet or cross, return True.
class Solution:
    def isPalindrome(self, s: str) -> bool:
        left, right = 0, len(s) - 1

        while left < right:
            # Ignore characters that are not letters or digits.
            while left < right and not s[left].isalnum():
                left += 1
            while left < right and not s[right].isalnum():
                right -= 1

            # Compare without regard to letter case.
            if s[left].lower() != s[right].lower():
                return False

            left += 1
            right -= 1

        return True

Complexity:

  • Time: O(n), where n is the string length; each pointer moves only inward.
  • Space: O(1), since the comparisons use no additional data structure.

Common follow-ups

  • What if the input contains no letters or digits? It is considered a palindrome, since there are no mismatching characters.
  • Can you avoid creating a normalized copy of the string? Yes; the two-pointer scan uses constant extra space.
  • How would you handle Unicode normalization? Normalize the string first if canonically equivalent characters should compare as equal; that may require additional space.
CodingEasyVKSoftware Engineer

4. 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.
CodingEasyVKSoftware Engineer

5. Summary Ranges (LeetCode)

Model answer

The task

Given a sorted array of distinct integers, combine each maximal run of consecutive values into a compact string. A run of one value is written as that value; a longer run uses its first and last values separated by an arrow.

Key idea

Scan the array once, keeping track of the start of the current run. When the next number is not consecutive, emit the completed run and begin a new one.

Approach

  1. Start at the first array element.
  2. Advance while each next value is exactly one greater than the current value.
  3. Emit the run as a single number or as a start-to-end range.
  4. Continue from the next unprocessed element.
  5. Return the collected strings.
from typing import List

class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        ranges = []
        i = 0

        while i < len(nums):
            start = nums[i]

            # Find the end of this consecutive run.
            while i + 1 < len(nums) and nums[i + 1] == nums[i] + 1:
                i += 1

            end = nums[i]
            if start == end:
                ranges.append(str(start))
            else:
                ranges.append(f"{start}->{end}")

            i += 1

        return ranges

Complexity:

  • Time: O(n), since each element is visited once.
  • Space: O(1) auxiliary space, excluding the output list.

Common follow-ups

  • What if duplicates are allowed? Skip duplicates during the scan so they do not break a consecutive run.
  • What if the input is not sorted? Sort it first, then deduplicate if needed; sorting takes O(n log n).
  • Can the ranges be generated from a stream? Keep the current run’s start and end, and emit it whenever the next value is not consecutive.
CodingEasyVKSoftware Engineer

6. Move Zeroes (LeetCode)

Model answer

The task

Rearrange an integer array in place so all zeroes come after the nonzero values. Keep the nonzero values in their original relative order.

Key idea

Use a write pointer to mark where the next nonzero value belongs. Scan the array once, swapping each nonzero value into that position; this keeps the nonzero values stable and uses constant extra space.

Approach

  1. Set write to the first available position for a nonzero value.
  2. Scan each index from left to right.
  3. When a nonzero value is found, swap it with the value at write.
  4. Advance write after each nonzero value.
  5. Once the scan ends, all remaining positions contain zeroes.
from typing import List

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        # The next nonzero value belongs at index write.
        write = 0

        for read in range(len(nums)):
            if nums[read] != 0:
                nums[write], nums[read] = nums[read], nums[write]
                write += 1

Complexity:

  • Time: O(n), where n is the array length; each value is examined once.
  • Space: O(1), since rearrangement is done in place.

Common follow-ups

  • What if relative order does not matter? Partitioning zeroes and nonzeroes can be done with two pointers, potentially with fewer assignments.
  • Can you reduce unnecessary writes? Swap only when read != write; this avoids self-swaps.
  • What if the input is a linked list? Relink nonzero nodes in their original order, then append the zero-valued nodes.
CodingMediumVKSoftware Engineer

7. Compare Version Numbers (LeetCode)

Model answer

The task

Compare two dot-separated version strings by their numeric components. Ignore leading zeros within a component, and treat components missing from the end of a version as zero.

Key idea

Scan both strings component by component, without splitting them or converting potentially long digit sequences to integers. Compare each pair by significant digit count, then lexicographically.

Approach

  1. Keep a pointer into each version string.
  2. Find the end of the current component in each string.
  3. Skip leading zeros, then compare the significant digit counts.
  4. If the counts match, compare digits from left to right.
  5. Advance past the components; treat an exhausted string as having zero-valued components.
class Solution:
    def compareVersion(self, version1: str, version2: str) -> int:
        i = j = 0
        n, m = len(version1), len(version2)

        while i < n or j < m:
            # Locate the current component in each version.
            if i < n:
                start1 = i
                while i < n and version1[i] != ".":
                    i += 1
                end1 = i
                i += 1  # Move past the dot, if present.
            else:
                start1 = end1 = 0

            if j < m:
                start2 = j
                while j < m and version2[j] != ".":
                    j += 1
                end2 = j
                j += 1
            else:
                start2 = end2 = 0

            # Ignore leading zeros.
            while start1 < end1 and version1[start1] == "0":
                start1 += 1
            while start2 < end2 and version2[start2] == "0":
                start2 += 1

            length1 = end1 - start1
            length2 = end2 - start2

            if length1 != length2:
                return 1 if length1 > length2 else -1

            for offset in range(length1):
                digit1 = version1[start1 + offset]
                digit2 = version2[start2 + offset]
                if digit1 != digit2:
                    return 1 if digit1 > digit2 else -1

        return 0

Complexity:

  • Time: O(n + m), where n and m are the string lengths.
  • Space: O(1), using only pointers and counters.

Common follow-ups

  • What if components are extremely long? Comparing significant lengths and digits avoids integer conversion limits.
  • What if a version has trailing zero components? They compare equal to omitted components.
  • Can the components be compared numerically after splitting? Yes, for ordinary-sized inputs, though it uses extra space and integer parsing.
CodingMediumVKSoftware Engineer

8. Permutation in String (LeetCode)

Model answer

The task

Determine whether the second string contains a contiguous substring that is a rearrangement of the first string.

Key idea

A rearrangement has the same character frequencies. Slide a window the length of the first string across the second, comparing each window’s frequency counts with the target counts.

Approach

  1. If the first string is longer, return False.
  2. Count the characters in the first string and the initial window of the second.
  3. Compare the two frequency arrays.
  4. Slide the window one character at a time: remove the outgoing character and add the incoming one.
  5. Return True as soon as the arrays match; otherwise return False after checking all windows.
class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        window_size = len(s1)

        if window_size > len(s2):
            return False

        # The input strings contain lowercase English letters.
        target = [0] * 26
        window = [0] * 26

        for i in range(window_size):
            target[ord(s1[i]) - ord("a")] += 1
            window[ord(s2[i]) - ord("a")] += 1

        if window == target:
            return True

        # Advance the fixed-size window through s2.
        for right in range(window_size, len(s2)):
            outgoing = ord(s2[right - window_size]) - ord("a")
            incoming = ord(s2[right]) - ord("a")

            window[outgoing] -= 1
            window[incoming] += 1

            if window == target:
                return True

        return False

Complexity:

  • Time: O(n), where n is the length of the second string; each window comparison checks a fixed 26 entries.
  • Space: O(1), using two fixed-size arrays for the lowercase alphabet.

Common follow-ups

  • What if the strings can contain arbitrary Unicode characters? Use hash maps for frequencies instead of fixed-size arrays.
  • Can the frequency comparison avoid checking all 26 counts each time? Track how many character counts currently match and update that value when sliding.
  • What if the goal is to find every matching window? Record each window’s starting index instead of returning at the first match.
CodingMediumVKSoftware Engineer

9. Maximize Distance to Closest Person (LeetCode)

Model answer

The task

Given a row of seats where 1 marks an occupied seat and 0 marks an empty one, find the largest possible distance to the nearest occupied seat after choosing one empty seat.

Key idea

An empty run at either end can use the whole run, since its nearest occupied seat is on one side. For a run between two occupied seats, the best seat is near the middle, giving a distance of run_length // 2.

Approach

  1. Scan the row from left to right, tracking the index of the most recent occupied seat.
  2. For the first occupied seat, record the length of the leading empty run.
  3. For each later occupied seat, compute the best distance within the gap from the previous occupied seat.
  4. After the scan, include the trailing empty run.
  5. Return the largest distance found.
from typing import List

class Solution:
    def maxDistToClosest(self, seats: List[int]) -> int:
        best = 0
        previous_occupied = -1

        for index, seat in enumerate(seats):
            if seat == 1:
                if previous_occupied == -1:
                    # The leading empty run has an occupied seat only to its right.
                    best = index
                else:
                    # A gap between occupied seats is best served from its middle.
                    gap_length = index - previous_occupied - 1
                    best = max(best, gap_length // 2)

                previous_occupied = index

        # The trailing empty run has an occupied seat only to its left.
        trailing_length = len(seats) - 1 - previous_occupied
        return max(best, trailing_length)

Complexity:

  • Time: O(n), where n is the number of seats, scanned once.
  • Space: O(1), using only a few variables.

Common follow-ups

  • Return the chosen seat index, not just the distance: Track the candidate index for each leading, internal, and trailing run.
  • Handle ties between equally good seats: Keep the first candidate, or apply a stated tie-breaking rule when comparing candidates.
  • Allow seats arranged in a circle: Consider the wraparound gap between the last and first occupied seats as another internal gap.
CodingMediumVKSoftware Engineer

10. 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.
CodingMediumVKSoftware Engineer

11. Longest Subarray of 1's After Deleting One Element (LeetCode)

Model answer

The task

Given a binary array, find the longest run of ones possible after deleting exactly one element.

Key idea

Use a sliding window that contains at most one zero. Deleting one element from a window leaves at most window length - 1 elements, so track that value as the answer.

Approach

  1. Expand the window one element at a time from the right.
  2. Count zeros in the current window.
  3. While there are more than one zero, advance the left edge until the window is valid again.
  4. Update the best result with the window length minus one. This also handles arrays containing only ones, where the deletion must still occur.
class Solution:
    def longestSubarray(self, nums: list[int]) -> int:
        left = 0
        zeros = 0
        best = 0

        for right, value in enumerate(nums):
            if value == 0:
                zeros += 1

            # Keep at most one zero, which can be removed.
            while zeros > 1:
                if nums[left] == 0:
                    zeros -= 1
                left += 1

            # One element must be deleted from the window.
            best = max(best, right - left)

        return best

Complexity:

  • Time: O(n), since each element enters and leaves the window at most once.
  • Space: O(1), using only a few counters.

Common follow-ups

  • What if the input can contain values other than 0 and 1? Define which values count as removable, then adapt the window condition.
  • What if up to k zeros may be deleted? Allow at most k zeros in the window and track window length - k.
  • What if the array is empty? The loop does not run, so the result is 0.
  • Can the input be modified? No modification is needed; the window only reads from the array.
CodingMediumVKSoftware Engineer

12. 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.

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