EPAM Systems interview questions & answers

20 real EPAM Systems interview questions with full model answers — Coding, Behavioral. Drawn from the same verified bank ChannelPulse drills from (58 EPAM Systems questions in total).

BehavioralEasyEPAM SystemsSoftware EngineerTechnical interview

1. Why did you come to India to study engineering?

Model answer

  1. Situation — I chose to come to India because I wanted to study engineering in an environment where strong academic foundations sit alongside a large, fast-growing technology sector. I was looking for more than a degree: I wanted to learn with people from different backgrounds and see how engineering is applied to practical problems.
  2. Task — My goal was to build a solid technical base while becoming comfortable adapting to a new academic and cultural setting. I also wanted to make a deliberate choice based on the quality and breadth of the opportunity, rather than choosing a destination simply because it was familiar.
  3. Action
  • I looked at the engineering curriculum and the opportunity to develop fundamentals in areas such as mathematics, programming, and systems—not only learn a particular tool or technology.
  • I considered India’s broad technology ecosystem and the exposure it could provide to different types of engineering work, from established companies to newer product teams.
  • I also valued studying in a diverse environment. Working with classmates who approach problems differently has helped me explain my reasoning, listen carefully, and collaborate across perspectives.
  • Moving for my studies required me to become more independent. I learned to manage my time, ask for help when appropriate, and adjust to new expectations without losing sight of my academic goals.
  • I have tried to make the most of the decision by connecting what I learn in class to practical projects and by building habits that will transfer into professional engineering work.
  1. Result — The experience has strengthened both my technical foundation and my ability to adapt. It also confirmed that I thrive in environments where I can keep learning, work with diverse teams, and apply engineering to real needs. That is one reason I am interested in a company such as EPAM, where collaboration and solving complex client problems are central to the work.
BehavioralMediumEPAM SystemsSoftware EngineerTechnical interview

2. Explain your CargoNepal project, including its structure, what it is, why you built it, and what you used to build it.

Model answer

  1. Situation — CargoNepal was a project I built to address a practical logistics problem: customers need a clear way to request and track cargo, while staff need a consistent way to manage shipments and status updates. I designed it as a small end-to-end web application rather than a static project, so it could demonstrate both the customer workflow and the operational side. I’d replace the example stack and details below with the exact ones from my implementation.
  2. Task — My goal was to make the shipment journey easy to understand—from creating a request through tracking delivery—while keeping the code organized enough to extend. The main constraint was delivering a usable MVP without overcomplicating the architecture.
  3. Action
  • I divided the application into a frontend, backend API, and database. The frontend contained pages and reusable components for registration, shipment creation, tracking, and staff operations.
  • I used React for the UI, Node.js with Express for REST endpoints, and MongoDB for shipment and user records. Authentication used JWT-based sessions, with authorization checks for customer and administrative actions.
  • I modeled a shipment around a tracking identifier, sender and receiver details, service information, and a sequence of status updates. That let users see progress rather than just a single current status.
  • I kept the repository organized by separating routes, controllers, data models, and shared middleware on the backend, and pages, components, and API calls on the frontend. I validated inputs at the API boundary and handled loading, error, and empty states in the UI.
  • I built the workflow incrementally: first create and retrieve shipments, then add authentication and status tracking, and finally refine the interface based on testing. That kept the core journey working throughout development.
  1. Result — The result was a working logistics MVP that showed how customers could submit and track cargo and how staff could update shipment progress. Building it taught me to treat status history, permissions, and clear failure states as core parts of a logistics product—not as details to add after the main screens. In a production setting, I’d next focus on auditability, notifications, observability, and integration with carrier systems.
BehavioralMediumEPAM SystemsSoftware EngineerTechnical interview

3. Describe your hackathon experience, including the technology stack, your role, and where the idea came from.

Model answer

  1. Situation — I took part in a 24-hour university hackathon with a small, cross-functional team. We noticed that students attending events on a large campus often struggled to find the right building and keep up with last-minute room changes. We wanted to build something useful within the time available, rather than a broad idea that would be difficult to demonstrate.
  2. Task — I owned the backend and helped the team turn the idea into a working end-to-end prototype. Our main constraint was time: we needed a simple, reliable demo by the final presentation, even if some features had to be deferred.
  3. Action
  • I helped narrow the scope to a campus event finder with location details and basic directions. We prioritized the main user journey and left out features such as accounts and personalized recommendations.
  • I used Node.js and Express to build the API, with MongoDB for event and location data. A teammate built the React interface, and I integrated it with the backend and a maps API.
  • I defined a small, clear data model and seeded realistic sample events so the demo would work consistently without depending on organizers entering live data.
  • When integration exposed mismatches between the frontend and API, I agreed on a response format with my teammate and added validation and useful error responses rather than patching each screen separately.
  • I kept the team focused by checking our remaining time against the demo’s critical path. We tested the complete flow early, then used the final hours to fix issues and prepare a concise presentation.
  1. Result — We delivered a working prototype that let a user find an event and view its location, and we presented the complete flow to the judges. The most valuable outcome was learning how quickly unclear scope and API assumptions can consume hackathon time. Since then, I try to agree on interfaces early, build a vertical slice first, and treat a successful demo as a team outcome—not just a coding result.
BehavioralHardEPAM SystemsSoftware EngineerGroup discussion

4. You are on the bank of a river full of crocodiles, with a lion and a tiger behind you.

The full question

You are on the bank of a river full of crocodiles, with a lion and a tiger behind you. How do you escape?

Model answer

  1. Situation — I’d treat this as an ambiguous, high-risk situation rather than assume there’s a clever trick that makes either predator or the crocodile-infested river safe. With animals on one side and a dangerous crossing on the other, a rushed move could make things worse. My immediate priority would be to create distance from the animals and get help without approaching the water.
  2. Task — The goal is to reach safety while minimizing exposure. Since the scenario doesn’t specify terrain, equipment, or how close the animals are, I wouldn’t claim there’s one guaranteed escape route.
  3. Action
  • I’d stay calm, avoid sudden movements, and assess the surroundings: nearby shelter, a vehicle, a sturdy barrier, higher ground, or a safe route away from both the river and the animals.
  • I’d move toward the safest available barrier or enclosed space without turning my back or running toward the river. I wouldn’t try to cross water known to contain crocodiles.
  • If I had a phone or radio, I’d contact local emergency services or park rangers, give my location, and follow their instructions. If others were present, I’d ask them to help communicate rather than have everyone scatter.
  • If the animals were closing in and no safe route were obvious, I’d use available cover and barriers to buy time, then move only when I had a clearer path. I’d avoid provoking, feeding, or trying to fight wildlife.
  • In an interview, I’d also clarify whether this is a literal safety scenario or a riddle. If it’s a riddle, the intended answer may be that it’s a dream and I should wake up—but I wouldn’t rely on that interpretation in a real emergency.
  1. Result — That approach avoids the most obvious hazard—entering crocodile-infested water—and prioritizes getting expert help and using the environment safely. The broader lesson is to identify assumptions, manage immediate risk, and choose a reversible action before committing to a dangerous one.
CodingEasyEPAM SystemsSoftware Engineer

5. 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.
CodingEasyEPAM SystemsSoftware Engineer

6. Roman to Integer (LeetCode)

Model answer

The task

Convert a string of Roman numeral symbols into its integer value. Roman numerals use a small set of symbols, with some smaller values placed before larger ones to indicate subtraction.

Key idea

Scan the string from left to right, comparing each symbol’s value with the next one. If the current value is smaller, subtract it; otherwise, add it. This handles subtractive pairs without needing to process them separately.

Approach

  1. Store the integer value for each Roman numeral symbol in a lookup table.
  2. Initialize a running total to zero.
  3. For each symbol, compare its value with the following symbol’s value, if one exists.
  4. Subtract the current value when it is smaller than the next value; otherwise, add it.
  5. Return the total. This assumes the input is a valid Roman numeral.
class Solution:
    def romanToInt(self, s: str) -> int:
        values = {
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000,
        }

        total = 0

        for i, symbol in enumerate(s):
            current = values[symbol]

            # A smaller value before a larger value is subtracted.
            if i + 1 < len(s) and current < values[s[i + 1]]:
                total -= current
            else:
                total += current

        return total

Complexity: Time: O(n), where n is the string length, since each symbol is visited once.

Complexity: Space: O(1), because the lookup table has a fixed number of entries.

Common follow-ups

  • How would you handle invalid Roman numeral strings? Validate symbol order and repetition rules before or during conversion.
  • How would you convert an integer to a Roman numeral? Greedily subtract from a descending list of allowed values, including subtractive pairs.
  • Can the conversion be done scanning right to left? Yes; subtract a value if it is smaller than the largest value already seen to its right, otherwise add it.
CodingEasyEPAM SystemsSoftware Engineer

7. 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.
CodingEasyEPAM SystemsSoftware Engineer

8. Palindrome Number (LeetCode)

Model answer

The task

Determine whether an integer reads the same from left to right and right to left. Negative values are not palindromes.

Key idea

Reverse only the last half of the digits, then compare it with the remaining first half. This avoids converting to a string and keeps the extra space constant.

Approach

  1. Return False for negative integers.
  2. Return False for positive integers ending in zero; zero itself is a palindrome.
  3. Repeatedly move the last digit from the number to a reversed-half accumulator.
  4. Stop when the accumulator has at least as many digits as the remaining number.
  5. Compare the halves directly for even digit counts, or discard the middle digit for odd counts.
class Solution:
    def isPalindrome(self, x: int) -> bool:
        # Negative numbers have a leading minus sign, so they cannot be palindromes.
        if x < 0:
            return False

        # A positive number ending in zero would need a leading zero to be palindromic.
        if x != 0 and x % 10 == 0:
            return False

        reversed_half = 0

        # Move digits until the reversed half is at least as long as the remaining half.
        while x > reversed_half:
            reversed_half = reversed_half * 10 + x % 10
            x //= 10

        # For an odd number of digits, ignore the middle digit.
        return x == reversed_half or x == reversed_half // 10

Complexity:

  • Time: O(log₁₀ n), for processing the digits of the number.
  • Space: O(1), using only a few integer variables.

Common follow-ups

  • How would you check a palindrome by converting to a string? Compare symmetric characters, using O(log n) extra space.
  • How would you avoid integer overflow in a fixed-width language? Reversing only half the digits keeps the accumulator bounded.
  • What about zero and numbers ending in zero? Zero is palindromic; other numbers ending in zero are not.
CodingEasyEPAM SystemsSoftware Engineer

9. 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.
CodingEasyEPAM SystemsSoftware Engineer

10. 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.
CodingEasyEPAM SystemsSoftware Engineer

11. Reverse Vowels of a String (LeetCode)

Model answer

The task

Given a string, return a new string with its vowels in reverse order. Keep every non-vowel character in its original position, and treat uppercase and lowercase vowels alike.

Key idea

Use two pointers, one at each end of the string. Move each pointer inward until it finds a vowel, then swap those vowels and continue.

Approach

  1. Convert the string to a list so its characters can be swapped.
  2. Put one pointer at the start and the other at the end.
  3. Advance the left pointer past non-vowels; retreat the right pointer past non-vowels.
  4. Swap the vowels when both pointers stop, then move both inward.
  5. Join the characters into the result.
class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = set("aeiouAEIOU")
        chars = list(s)
        left, right = 0, len(chars) - 1

        while left < right:
            while left < right and chars[left] not in vowels:
                left += 1
            while left < right and chars[right] not in vowels:
                right -= 1

            chars[left], chars[right] = chars[right], chars[left]
            left += 1
            right -= 1

        return "".join(chars)

Complexity:

  • Time: O(n), since the pointers traverse the string at most once.
  • Space: O(n), for the character list used to build the result.

Common follow-ups

  • How would you handle a different definition of vowels? Change the membership set to match it.
  • Can the method avoid creating a character list? Not for an immutable Python string; a mutable buffer would be needed.
  • What if there are no vowels or only one vowel? The pointers never swap distinct positions, so the string is returned unchanged.
CodingEasyEPAM SystemsSoftware Engineer

12. Merge Two Sorted Lists (LeetCode)

Model answer

The task

Given the heads of two sorted singly linked lists, combine their nodes into one sorted list. Return the head of the merged list.

Key idea

At each step, append the smaller of the two current nodes, then advance that list. A dummy node simplifies handling the merged list’s head.

Approach

  1. Create a dummy node and set a pointer to it.
  2. While both lists have nodes, compare their values.
  3. Link the smaller node after the pointer and advance its source list.
  4. Advance the pointer.
  5. Link any remaining nodes and return the node after the dummy.
# LeetCode provides the ListNode class.
class Solution:
    def mergeTwoLists(self, list1, list2):
        dummy = ListNode(0)
        tail = dummy

        # Repeatedly attach the smaller current node.
        while list1 and list2:
            if list1.val <= list2.val:
                tail.next = list1
                list1 = list1.next
            else:
                tail.next = list2
                list2 = list2.next

            tail = tail.next

        # At most one list remains; it is already sorted.
        tail.next = list1 if list1 else list2
        return dummy.next

Complexity:

  • Time: O(m + n), where m and n are the lengths of the lists.
  • Space: O(1) extra space; the existing nodes are relinked.

Common follow-ups

  • How would you implement this recursively? Choose the smaller head and recursively merge the rest; this uses O(m + n) call-stack space.
  • What if the lists are sorted in descending order? Adjust the comparison or reverse the merged result, depending on the desired output order.
  • What if one list is empty? The remaining list is returned directly.
CodingEasyEPAM SystemsSoftware Engineer

13. Longest Common Prefix (LeetCode)

Model answer

The task

Given a list of strings, return the longest string that is a prefix of every entry. If there is no shared prefix, return an empty string.

Key idea

Compare characters at the same position across all strings, starting from the first string. Stop at the first mismatch or when any string runs out.

Approach

  1. If the list is empty, return an empty string.
  2. Scan each character of the first string from left to right.
  3. For each position, compare that character with the character at the same position in every other string.
  4. If a string is too short or a character differs, return the matching prefix before that position.
  5. If all positions match, return the first string.
from typing import List

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""

        first = strs[0]

        for i, char in enumerate(first):
            for word in strs[1:]:
                if i == len(word) or word[i] != char:
                    return first[:i]

        return first

Complexity:

  • Time: O(S), where S is the total number of characters inspected.
  • Space: O(1) auxiliary space, excluding the returned prefix.

Common follow-ups

  • How would you handle many prefix queries over the same set of strings? Build a trie once, then traverse it to find shared prefixes.
  • Could sorting help? Yes. Sort the strings and compare only the first and last; their common prefix is shared by all strings.
  • What if strings arrive as a stream? Keep a running prefix and shorten it as each new string arrives.
CodingEasyEPAM SystemsSoftware Engineer

14. 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.
CodingEasyEPAM SystemsSoftware Engineer

15. 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.
CodingEasyEPAM SystemsSoftware Engineer

16. First Unique Character in a String (LeetCode)

Model answer

The task

Return the index of the first character in a string that occurs exactly once. If no character is unique, return -1.

Key idea

Count how often each character appears, then scan the string from left to right. The first character with a count of one has the smallest qualifying index.

Approach

  1. Build a frequency map by counting every character.
  2. Scan the string in its original order.
  3. Return the index of the first character whose count is one.
  4. If the scan finishes without finding one, return -1.
class Solution:
    def firstUniqChar(self, s: str) -> int:
        # Count the occurrences of each character.
        counts = {}
        for char in s:
            counts[char] = counts.get(char, 0) + 1

        # Return the earliest character that appears once.
        for index, char in enumerate(s):
            if counts[char] == 1:
                return index

        return -1

Complexity:

  • Time: O(n), for counting and scanning the string.
  • Space: O(k), where k is the number of distinct characters stored in the map.

Common follow-ups

  • What if the string is streamed and cannot be revisited? Keep character counts and a queue of candidates; discard candidates once their count exceeds one.
  • What if characters come from a fixed, small alphabet? Use an array of counters instead of a hash map.
  • How would you return the unique character rather than its index? Return char at the matching position, with an appropriate sentinel if none exists.
CodingEasyEPAM SystemsSoftware Engineer

17. Reverse Linked List (LeetCode)

Model answer

The task

Given the head of a singly linked list, reverse its links in place and return the new head.

Key idea

Recursively reverse the list starting at the second node. As the recursion unwinds, point each node’s successor back to it, then clear its old forward link.

Approach

  1. If the list has zero or one node, it is already reversed.
  2. Recursively reverse the list after the head and save its new head.
  3. Point the next node back to the current node.
  4. Set the current node’s next pointer to None to finish the reversed list.
  5. Return the saved new head.
class Solution:
    def reverseList(self, head):
        # An empty or single-node list is already reversed.
        if head is None or head.next is None:
            return head

        # Reverse the remainder of the list.
        new_head = self.reverseList(head.next)

        # Put the current node after its former successor.
        head.next.next = head
        head.next = None

        return new_head

Complexity:

  • Time: O(n), where n is the number of nodes.
  • Space: O(n), for the recursive call stack.

Common follow-ups

  • Can you do it iteratively with O(1) extra space? Use previous, current, and next_node pointers to reverse links while traversing.
  • What if the list is empty or has one node? The base case returns it unchanged.
  • Can you reverse only a portion of the list? Track the sublist boundaries and reconnect them after reversing that segment.
CodingEasyEPAM SystemsSoftware Engineer

18. Reverse String (LeetCode)

Model answer

The task

Reverse the sequence of characters in place. The method should modify the given list rather than create and return a reversed copy.

Key idea

Use two pointers, one at each end of the list. Swap their characters, then move both pointers inward until they meet or cross.

Approach

  1. Set left to the first index and right to the last.
  2. While left < right, swap the characters at those indices.
  3. Advance left and decrease right.
  4. Stop once the pointers meet or cross; the list has been reversed.
from typing import List

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """Reverse s in place."""
        left = 0
        right = len(s) - 1

        while left < right:
            s[left], s[right] = s[right], s[left]
            left += 1
            right -= 1

Complexity:

  • Time: O(n), where n is the number of characters; each character is involved in at most one swap.
  • Space: O(1), since the reversal uses only two index variables and swaps in place.

Common follow-ups

  • Reverse only a subrange: Initialize the pointers to the subrange’s endpoints and use the same swap loop.
  • Reverse an immutable string: Convert it to a mutable character list, reverse that list, then join it into a new string.
  • Handle Unicode grapheme clusters: Reverse grapheme clusters rather than code points, since a visible character can consist of multiple code points.
CodingEasyEPAM SystemsSoftware Engineer

19. 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.
CodingEasyEPAM SystemsSoftware Engineer

20. Counter (LeetCode)

Model answer

The task

Create a function that returns another function. Each call to the returned function produces the next integer, starting from the supplied value.

Key idea

Keep the current value in a closure so it persists between calls. Return that value before incrementing it.

Approach

  1. Store the starting value in a local variable.
  2. Define an inner function that can modify that variable.
  3. In the inner function, save the current value, increment the stored value, and return the saved value.
  4. Return the inner function.
def createCounter(n: int):
    current = n

    def counter() -> int:
        nonlocal current  # Allow the inner function to update the enclosing variable.
        result = current
        current += 1
        return result

    return counter

Complexity:

  • Time: O(1) per call; each call performs a fixed number of operations.
  • Space: O(1); the closure retains only the current value.

Common follow-ups

  • How would you support decrementing or a custom step? Store the step and add it instead of always adding one.
  • How would you add a reset operation? Return a callable object or provide another function that restores the initial value.
  • What if multiple threads call the counter? Protect the read-and-increment operation with a lock.

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