Zoho interview questions & answers

20 real Zoho interview questions with full model answers — System design, Behavioral, Technical, Coding. Drawn from the same verified bank ChannelPulse drills from (148 Zoho questions in total).

BehavioralEasyZohoSoftware Engineer

1. Which programming language are you strongest in?

Model answer

  1. Situation — Java is the language I’m strongest in. I’ve used it for object-oriented application development, where correctness, maintainability, and clear interfaces matter as much as getting a feature working.
  2. Task — When I work in Java, I aim to deliver code that is easy for a team to understand and extend—not just code that passes the immediate test.
  3. Action
  • I use Java’s type system and interfaces to make responsibilities explicit. For example, I’d define a NotificationSender interface and separate email or in-app implementations, so callers don’t depend on a specific delivery mechanism.
  • I pay attention to collections, generics, and immutability to make data handling safer and reduce accidental state changes.
  • I handle errors deliberately: exceptions communicate failure, while validation and clear method contracts prevent avoidable errors.
  • I use tests to check behavior, including edge cases, and I’m comfortable debugging by tracing the call path and inspecting state rather than guessing.
  • I also try to choose the simplest appropriate design. I avoid adding abstractions until they solve a real problem, while keeping code structured enough to support future changes.
  1. Result — Java is the language I’d choose first for a backend task where I can apply those strengths, and I can explain my design choices and trade-offs as I implement it. I’m also comfortable learning another language when a project calls for it; the fundamentals transfer, but I make a point of learning the language’s idioms rather than writing Java in disguise.
CodingEasyZohoSoftware Engineer

2. Day of the Week (LeetCode)

Model answer

The task

Given a valid Gregorian calendar date, return its weekday name, such as "Monday" or "Friday".

Key idea

Count the number of days between the given date and a known date: January 1, 1971, which was a Friday. Gregorian leap-year rules let us count the intervening days in constant time, then use modulo 7 to find the weekday.

Approach

  1. Count all days in the complete years from 1971 up to, but not including, the given year.
  2. Count leap years in that range using the Gregorian rule: divisible by 4, except centuries unless divisible by 400.
  3. Add the days in the completed months of the given year, accounting for February in a leap year.
  4. Add the days elapsed in the given month.
  5. Offset from Friday by the total number of days modulo 7.
class Solution:
    def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
        weekdays = [
            "Monday", "Tuesday", "Wednesday", "Thursday",
            "Friday", "Saturday", "Sunday"
        ]
        days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

        def leap_year_count_through(y: int) -> int:
            return y // 4 - y // 100 + y // 400

        # Count days in complete years since 1971.
        previous_year = year - 1
        complete_years = year - 1971
        leap_years = (
            leap_year_count_through(previous_year)
            - leap_year_count_through(1970)
        )
        elapsed_days = 365 * complete_years + leap_years

        # Add days in complete months of the current year.
        if self._is_leap_year(year):
            days_in_month[1] = 29
        elapsed_days += sum(days_in_month[:month - 1])

        # Add days elapsed in the current month.
        elapsed_days += day - 1

        # January 1, 1971 was Friday, weekday index 4.
        return weekdays[(4 + elapsed_days) % 7]

    def _is_leap_year(self, year: int) -> bool:
        return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

Complexity:

  • Time: O(1), since the month list has a fixed size.
  • Space: O(1), using a fixed-size month list and weekday list.

Common follow-ups

  • How would you handle dates before the reference date? Use a signed day difference and normalize with modulo 7.
  • How do you validate an input date? Check the month range and compare the day with that month’s length, including leap-year February.
  • How would you support another calendar system? Replace the month-length and leap-year rules with that calendar’s rules.
CodingEasyZohoSoftware Engineer

3. Find the Index of the First Occurrence in a String (LeetCode)

Model answer

The task

Given a text string and a pattern string, return the starting index of the pattern’s first occurrence in the text. Return -1 if it does not occur; an empty pattern matches at index 0.

Key idea

Use Knuth–Morris–Pratt (KMP). Its prefix table lets the search reuse information about matched characters instead of restarting from scratch after a mismatch.

Approach

  1. Build a prefix table for the pattern. At each position, it records the length of the longest proper prefix that is also a suffix.
  2. Scan the text while tracking how many pattern characters currently match.
  3. On a mismatch, use the prefix table to find the next viable match length.
  4. Return the match’s starting index when the entire pattern matches; otherwise return -1.
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if not needle:
            return 0

        # Build the longest-prefix-suffix table for needle.
        lps = [0] * len(needle)
        prefix_len = 0
        i = 1

        while i < len(needle):
            if needle[i] == needle[prefix_len]:
                prefix_len += 1
                lps[i] = prefix_len
                i += 1
            elif prefix_len > 0:
                prefix_len = lps[prefix_len - 1]
            else:
                i += 1

        # Search haystack without rechecking matched characters.
        text_i = 0
        pattern_i = 0

        while text_i < len(haystack):
            if haystack[text_i] == needle[pattern_i]:
                text_i += 1
                pattern_i += 1

                if pattern_i == len(needle):
                    return text_i - pattern_i
            elif pattern_i > 0:
                pattern_i = lps[pattern_i - 1]
            else:
                text_i += 1

        return -1

Complexity:

  • Time: O(n + m), where n and m are the text and pattern lengths.
  • Space: O(m), for the prefix table.

Common follow-ups

  • How would you handle many pattern searches in the same text? Build an index or use a multi-pattern algorithm such as Aho–Corasick.
  • What if the text arrives as a stream? Keep the KMP match state and prefix table between chunks.
  • How would you find all occurrences? After each full match, record its start and reset the pattern index using the final prefix-table value.
CodingEasyZohoSoftware Engineer

4. Island Perimeter (LeetCode)

Model answer

The task

Given a grid of land and water cells, calculate the total length of the land’s outer boundary. Each cell is square, and only sides next to water or outside the grid count.

Key idea

Start with four sides for every land cell. Subtract one for each side shared with another land cell; equivalently, count a side only when its neighbor is water or out of bounds.

Approach

  1. Record the grid’s row and column counts.
  2. Visit every cell.
  3. For each land cell, check its four neighboring positions.
  4. Add one to the perimeter for each neighbor that is outside the grid or water.
  5. Return the accumulated perimeter.
from typing import List

class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        rows = len(grid)
        cols = len(grid[0])
        perimeter = 0

        # Each exposed side of a land cell contributes one unit.
        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))

        for row in range(rows):
            for col in range(cols):
                if grid[row][col] == 0:
                    continue

                for dr, dc in directions:
                    neighbor_row = row + dr
                    neighbor_col = col + dc

                    # An out-of-grid or water neighbor leaves this side exposed.
                    if (
                        neighbor_row < 0
                        or neighbor_row >= rows
                        or neighbor_col < 0
                        or neighbor_col >= cols
                        or grid[neighbor_row][neighbor_col] == 0
                    ):
                        perimeter += 1

        return perimeter

Complexity:

  • Time: O(RC), where R and C are the grid dimensions; each cell checks four neighbors.
  • Space: O(1), excluding the input grid; only a fixed number of variables are used.

Common follow-ups

  • Can you use DFS or BFS? Yes; traverse the island and count exposed sides for each visited land cell, though a full grid scan is simpler.
  • What if the grid has multiple islands? The same scan returns the sum of their perimeters.
  • How would you handle a very large grid that does not fit in memory? Process it in chunks while retaining boundary rows or columns needed to check neighbors.
CodingEasyZohoSoftware Engineer

5. Find Missing and Repeated Values (LeetCode)

Model answer

The task

Given an \(n \times n\) grid containing values from 1 through \(n^2\), find the value that appears twice and the value that is missing. Return them in that order.

Key idea

Compare the grid’s sum and sum of squares with the corresponding sums for the complete range. Their differences reveal the sum and difference of the repeated and missing values, which lets us recover both using constant extra space.

Approach

  1. Let \(N=n^2\), and compute the expected sum and sum of squares of values from 1 to \(N\).
  2. Scan the grid to compute its actual sum and sum of squares.
  3. Subtract expected values from actual values. The sum difference is repeated - missing.
  4. Divide the square-sum difference by the sum difference to get repeated + missing.
  5. Solve for each value and return the repeated value first.
class Solution:
    def findMissingAndRepeatedValues(self, grid: list[list[int]]) -> list[int]:
        n = len(grid)
        total = n * n

        expected_sum = total * (total + 1) // 2
        expected_square_sum = total * (total + 1) * (2 * total + 1) // 6

        actual_sum = 0
        actual_square_sum = 0

        for row in grid:
            for value in row:
                actual_sum += value
                actual_square_sum += value * value

        difference = actual_sum - expected_sum
        square_difference = actual_square_sum - expected_square_sum

        # difference = repeated - missing
        # square_difference / difference = repeated + missing
        pair_sum = square_difference // difference

        repeated = (pair_sum + difference) // 2
        missing = (pair_sum - difference) // 2

        return [repeated, missing]

Complexity:

  • Time: O(n²), to scan every grid cell.
  • Space: O(1), using only a fixed number of variables.

Common follow-ups

  • What if the grid is too large for fixed-width sums? Use a hash map or wider integer type to avoid overflow.
  • How would you solve it without relying on square sums? Count occurrences while scanning, using O(n²) extra space in the worst case.
  • What if there are multiple repeated or missing values? The two-equation method is insufficient; track counts or use additional independent aggregates.
CodingEasyZohoSoftware Engineer

6. Find Winner on a Tic Tac Toe Game (LeetCode)

Model answer

The task

Given the sequence of moves in a 3×3 tic-tac-toe game, determine whether player A or B has won. If neither has won, report whether the game is a draw or still in progress.

Key idea

Track how many marks each player has placed in every row, column, and diagonal. A player wins as soon as any count reaches three.

Approach

  1. Create counters for each player’s rows, columns, and two diagonals.
  2. Process moves in order, alternating players starting with A.
  3. Increment the relevant row and column counters for the current move.
  4. If the move is on a diagonal, increment that diagonal’s counter too.
  5. Return the winner immediately when any counter reaches three.
  6. If all moves are processed, return a draw if the board is full; otherwise, return that the game is pending.
from typing import List

class Solution:
    def tictactoe(self, moves: List[List[int]]) -> str:
        # A counters are positive; B counters are negative.
        rows = [0] * 3
        cols = [0] * 3
        diagonals = [0, 0]

        for turn, (row, col) in enumerate(moves):
            value = 1 if turn % 2 == 0 else -1

            rows[row] += value
            cols[col] += value

            if row == col:
                diagonals[0] += value
            if row + col == 2:
                diagonals[1] += value

            if (
                abs(rows[row]) == 3
                or abs(cols[col]) == 3
                or abs(diagonals[0]) == 3
                or abs(diagonals[1]) == 3
            ):
                return "A" if value == 1 else "B"

        return "Draw" if len(moves) == 9 else "Pending"

Complexity:

  • Time: O(m), where m is the number of moves.
  • Space: O(1), using a fixed number of counters.

Common follow-ups

  • How would you support an n×n board? Track n rows, n columns, and the two diagonals; a count of n indicates a win.
  • Can you avoid scanning the whole move list after someone wins? Yes; this solution checks for a win after each move and returns immediately.
  • How should the logic change if players can make consecutive moves? Track the player explicitly instead of deriving it from the turn index.
CodingEasyZohoSoftware Engineer

7. 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.
CodingEasyZohoSoftware Engineer

8. 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.
CodingEasyZohoSoftware Engineer

9. Rotate String (LeetCode)

Model answer

The task

Determine whether one string can be obtained by repeatedly moving the first character of another string to its end. The resulting string must match exactly.

Key idea

A rotation of s appears as a substring of s + s. Check for that match using KMP string matching, which runs in linear time.

Approach

  1. If the strings have different lengths, they cannot be rotations.
  2. Build the KMP prefix table for the target string.
  3. Scan s + s with KMP, returning True if the target is found.
  4. Return False if the scan finishes without a match.
class Solution:
    def rotateString(self, s: str, goal: str) -> bool:
        if len(s) != len(goal):
            return False
        if not goal:
            return True

        # Build the KMP prefix table: the longest proper prefix that
        # is also a suffix for each prefix of goal.
        prefix = [0] * len(goal)
        matched = 0

        for i in range(1, len(goal)):
            while matched and goal[i] != goal[matched]:
                matched = prefix[matched - 1]
            if goal[i] == goal[matched]:
                matched += 1
                prefix[i] = matched

        # Search for goal in the doubled string.
        matched = 0
        for char in s + s:
            while matched and char != goal[matched]:
                matched = prefix[matched - 1]
            if char == goal[matched]:
                matched += 1
                if matched == len(goal):
                    return True

        return False

Complexity:

  • Time: O(n), for building the prefix table and scanning the doubled string.
  • Space: O(n), for the prefix table.

Common follow-ups

  • Can you use a built-in string search instead? Yes: check whether goal occurs in s + s; KMP gives an explicit linear-time bound.
  • What if the strings have different lengths? They cannot be rotations, so return False immediately.
  • Does the empty string match itself? Yes; zero rotations leave it unchanged.
CodingEasyZohoSoftware Engineer

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

11. 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.
CodingEasyZohoSoftware Engineer

12. Buddy Strings (LeetCode)

Model answer

The task

Determine whether swapping exactly two positions in one string can make it equal to another string of the same length.

Key idea

If the strings differ, they must have exactly two mismatched positions, and swapping those characters must fix both. If they already match, a valid swap is possible only when some character appears more than once.

Approach

  1. If the strings have different lengths, return False.
  2. If they are equal, check whether the first string contains a repeated character.
  3. Otherwise, collect the positions where the characters differ.
  4. Return True only when there are exactly two such positions and their characters match in reverse order.
class Solution:
    def buddyStrings(self, s: str, goal: str) -> bool:
        if len(s) != len(goal):
            return False

        if s == goal:
            # Swapping equal characters leaves the string unchanged.
            return len(set(s)) < len(s)

        mismatches = []
        for i, (left, right) in enumerate(zip(s, goal)):
            if left != right:
                mismatches.append(i)
                if len(mismatches) > 2:
                    return False

        if len(mismatches) != 2:
            return False

        i, j = mismatches
        return s[i] == goal[j] and s[j] == goal[i]

Complexity:

  • Time: O(n), for comparing the strings and checking for duplicates.
  • Space: O(1), since the character set is fixed; the mismatch list holds at most two positions.

Common follow-ups

  • What if the strings are already equal but all characters are unique? No swap can leave the string unchanged, so return False.
  • Can the mismatch scan stop early? Yes; as soon as a third mismatch is found, the answer must be False.
  • What if the character set is not fixed? The duplicate check may use O(n) space for a set of distinct characters.
CodingEasyZohoSoftware Engineer

13. 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.
CodingEasyZohoSoftware Engineer

14. Isomorphic Strings (LeetCode)

Model answer

The task

Determine whether two strings have the same length and whether their characters can be matched one-to-one so that each position in one string corresponds to the same position in the other.

Key idea

Maintain mappings in both directions. A character in the first string must always map to the same character in the second, and two different characters cannot map to the same character.

Approach

  1. Return False if the strings have different lengths.
  2. Create a mapping from the first string to the second.
  3. Create a reverse mapping from the second string to the first.
  4. Scan corresponding characters together.
  5. If either mapping conflicts with the current pair, return False; otherwise, record the pair.
  6. If every pair is consistent, return True.
class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False

        forward = {}
        reverse = {}

        for left, right in zip(s, t):
            if left in forward and forward[left] != right:
                return False
            if right in reverse and reverse[right] != left:
                return False

            forward[left] = right
            reverse[right] = left

        return True

Complexity:

  • Time: O(n), where n is the string length; each position is checked once.
  • Space: O(k), where k is the number of distinct characters stored in the mappings.

Common follow-ups

  • What if the mapping only needs to preserve characters in one direction? Use just one mapping; this does not enforce a one-to-one correspondence.
  • What if the strings are streamed? Process corresponding characters as they arrive, retaining the two mappings.
  • Can the extra space be bounded for a fixed alphabet? Yes; use arrays instead of dictionaries when the character set has a known, small range.
CodingEasyZohoSoftware Engineer

15. Lemonade Change (LeetCode)

Model answer

The task

Given customers’ bill denominations in payment order, determine whether each customer can receive exact change when each lemonade costs $5. Begin with no change in the register.

Key idea

Track the number of $5 and $10 bills. For a $10 bill, give one $5 bill; for a $20 bill, use a $10 and a $5 if possible, preserving $5 bills for later.

Approach

  1. Initialize counts of $5 and $10 bills to zero.
  2. For a $5 bill, add it to the register.
  3. For a $10 bill, require and use one $5 bill, then record the $10.
  4. For a $20 bill, prefer one $10 and one $5; otherwise use three $5 bills.
  5. Return False if any required change is unavailable; otherwise return True.
from typing import List

class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        fives = 0
        tens = 0

        for bill in bills:
            if bill == 5:
                fives += 1
            elif bill == 10:
                if fives == 0:
                    return False
                fives -= 1
                tens += 1
            else:  # bill == 20
                # Prefer using a $10 and a $5, preserving smaller bills.
                if tens > 0 and fives > 0:
                    tens -= 1
                    fives -= 1
                elif fives >= 3:
                    fives -= 3
                else:
                    return False

        return True

Complexity:

  • Time: O(n), where n is the number of customers.
  • Space: O(1), using only two counters.

Common follow-ups

  • What if the price changes? Track received denominations and find a valid change combination for the new price.
  • Why prefer a $10 plus a $5 over three $5 bills? Smaller bills are more flexible for future transactions.
  • What if bills arrive concurrently? Protect the register’s counts and each payment update with a lock.
CodingEasyZohoSoftware Engineer

16. Long Pressed Name (LeetCode)

Model answer

The task

Determine whether typed could result from entering name while occasionally holding a key long enough to produce extra copies of that character.

Key idea

Scan typed from left to right while tracking the next character expected from name. Each character must either match that expected character, or be an extra copy of the previous character in typed.

Approach

  1. Set a pointer to the first character of name.
  2. For each character in typed, advance the pointer when it matches the next expected character.
  3. Otherwise, accept it only if it repeats the preceding character in typed.
  4. Return true only if every character of name was matched.
class Solution:
    def isLongPressedName(self, name: str, typed: str) -> bool:
        name_index = 0

        for typed_index, char in enumerate(typed):
            if name_index < len(name) and char == name[name_index]:
                name_index += 1
            elif typed_index == 0 or char != typed[typed_index - 1]:
                # This is neither the next expected character
                # nor an extra copy of the previous typed character.
                return False

        # All characters from name must have been matched.
        return name_index == len(name)

Complexity:

  • Time: O(len(typed)) — each character is checked once.
  • Space: O(1) — only pointers are used.

Common follow-ups

  • Can you compare character runs instead? Yes; each character’s run in typed must match the corresponding run in name and be at least as long.
  • What if typed is shorter than name? The final pointer check rejects it because not all of name was matched.
  • Can this process a stream of typed characters? Yes; keep the name pointer and previous typed character as state, then apply the same checks to each arriving character.
CodingEasyZohoSoftware Engineer

17. Reverse Words in a String III (LeetCode)

Model answer

The task

Reverse the characters within each word of a string while keeping the words in their original order and preserving the spaces.

Key idea

Scan the string to find each word’s boundaries, then reverse that range in a mutable character array with two pointers. The scan moves forward once, and each character is swapped at most once.

Approach

  1. Convert the string to a list of characters so its contents can be swapped.
  2. Scan from left to right, skipping spaces to find the start of each word.
  3. Find the word’s end, then swap characters inward from both ends.
  4. Continue after the word and return the characters joined into a string.
class Solution:
    def reverseWords(self, s: str) -> str:
        chars = list(s)
        n = len(chars)
        i = 0

        while i < n:
            # Skip spaces between words.
            if chars[i] == " ":
                i += 1
                continue

            # Find the bounds of this word.
            left = i
            while i < n and chars[i] != " ":
                i += 1
            right = i - 1

            # Reverse the word in place.
            while left < right:
                chars[left], chars[right] = chars[right], chars[left]
                left += 1
                right -= 1

        return "".join(chars)

Complexity:

  • Time: O(n), where n is the length of the string.
  • Space: O(n), for the mutable character array and returned string.

Common follow-ups

  • How would you reverse the words in the string’s character array in place? Use the same boundary scan and swap ranges directly.
  • What if spaces may appear at the beginning or end? The scan skips spaces, so they remain unchanged.
  • What if words are separated by arbitrary whitespace? Treat any whitespace character as a separator when locating word boundaries.
System designHardZohoSoftware EngineerAdvanced Programming round

18. Build an application like Zomato with customer and delivery-person logins, an ordering procedure, and an option to log out.

Model answer

1. Requirements & scale

Functional requirements

  • Customers sign up/log in, browse nearby restaurants and menus, place and pay for orders, track delivery, and log out.
  • Delivery partners log in, receive eligible delivery offers, accept jobs, update delivery status, and log out.
  • Restaurants can accept or reject orders and update preparation status.
  • Support order history, notifications, and cancellation rules.

Non-functional requirements

  • Highly available browsing and order placement; durable order and payment records.
  • Secure role-based access, idempotent order creation, and auditable status changes.
  • Location-aware discovery and delivery assignment with low latency.

Estimates: Assume 5 million daily users, 500,000 orders/day, and 30,000 peak browse requests/second. At roughly 3 KB of order and status data per order, that is about 550 GB/year raw; indexes and replicas may bring this to 1–2 TB/year. If cached browse responses average 5 KB, peak egress is about 150 MB/s. These estimates guide partitioning and cache capacity, not a fixed launch requirement.

2. High-level architecture

flowchart TD
  subgraph C[Client]
    App[Customer app]
    Rider[Delivery app]
    Restaurant[Restaurant portal]
  end
  subgraph E[Edge CDN]
    CDN[CDN and WAF]
  end
  subgraph L[Load Balancer]
    LB[Regional load balancer]
  end
  subgraph S["API / Services"]
    Auth[Auth service]
    Catalog[Restaurant and menu service]
    Orders[Order service]
    Pay[Payment adapter]
    Dispatch[Dispatch service]
    Track[Tracking service]
    Notify[Notification service]
  end
  subgraph CCH[Cache]
    Redis[Redis cache and sessions]
  end
  subgraph D[Datastores]
    SQL[(Orders and accounts SQL)]
    Search[(Restaurant search index)]
    Geo[(Live location store)]
    Blob[(Images object storage)]
  end
  subgraph MQ[Message Queue]
    Events[Order and delivery events]
  end
  subgraph W[Workers]
    Assign[Dispatch workers]
    NotifyWorker[Notification workers]
  end
  App -->|HTTPS requests| CDN
  Rider -->|HTTPS and location| CDN
  Restaurant -->|HTTPS requests| CDN
  CDN -->|filtered traffic| LB
  LB -->|API requests| Auth
  LB -->|browse queries| Catalog
  LB -->|create and track order| Orders
  LB -->|partner actions| Dispatch
  LB -->|live updates| Track
  Auth -->|session lookup| Redis
  Catalog -->|cache then query| Redis
  Catalog -->|search| Search
  Catalog -->|image URLs| Blob
  Orders -->|transaction| SQL
  Orders -->|authorize and capture| Pay
  Orders -->|publish status event| Events
  Dispatch -->|read and write locations| Geo
  Events -->|order placed or accepted| Assign
  Assign -->|offers and assignments| Dispatch
  Events -->|status changes| NotifyWorker
  NotifyWorker -->|push or SMS| Notify
  Track -->|read current location| Geo
Diagram

Clients use HTTPS; location updates and tracking can use WebSockets or a short-interval polling fallback. The CDN serves static assets, while the WAF and load balancer protect and distribute API traffic.

3. API design

  • POST /v1/auth/login — authenticate and issue access and refresh credentials for a customer or delivery partner.
  • POST /v1/auth/logout — revoke the refresh session and invalidate the active session.
  • GET /v1/restaurants?lat=&lng=&radius= — discover nearby restaurants.
  • GET /v1/restaurants/{id}/menu — fetch menu and availability.
  • POST /v1/orders — place an order; require an Idempotency-Key.
  • GET /v1/orders/{id} — retrieve order state and tracking details.
  • POST /v1/delivery/offers/{id}/accept and POST /v1/delivery/orders/{id}/status — accept a delivery and report pickup/drop-off.
  • POST /v1/restaurants/orders/{id}/accept — restaurant accepts or rejects an order.

4. Data model & storage

  • SQL: users(id, role, status), sessions(id, user_id, expires_at, revoked_at), restaurants(id, location, status), menu_items(id, restaurant_id, price, available), orders(id, customer_id, restaurant_id, status, total, payment_id, created_at), and append-only order_events(order_id, status, timestamp, actor_id). Keep order creation and its initial event in one transaction. Partition orders by creation month; shard at larger scale by order_id, with customer and restaurant indexes for history and operations.
  • Search index: restaurant location, cuisine, and searchable menu fields; treat it as a rebuildable discovery index, not the source of truth.
  • Redis: short-lived menu/discovery caches, rate limits, and session lookup/revocation data.
  • Geospatial store: frequently updated partner locations with expiry; object storage holds restaurant images.

5. Deep dive

Order creation must handle retries, payment failures, and asynchronous restaurant/driver actions without losing or duplicating an order. The order service validates the customer, restaurant availability, item prices, and delivery zone against authoritative data. It creates a PENDING_PAYMENT order in SQL under an idempotency key, so a repeated request returns the same order rather than charging twice. It authorizes payment, then commits PLACED and an outbox event in the same database transaction. An outbox publisher sends that event to the queue; consumers can safely retry because they track processed event IDs.

sequenceDiagram
  participant C as Customer
  participant O as Order service
  participant DB as SQL database
  participant P as Payment provider
  participant Q as Event queue
  participant R as Restaurant
  participant D as Dispatch worker
  C->>O: POST order with idempotency key
  O->>DB: Validate and create pending order
  O->>P: Authorize payment
  P-->>O: Authorization result
  O->>DB: Commit placed state and outbox event
  O-->>C: Order ID and current status
  DB-->>Q: Publish order placed event
  Q-->>R: Request restaurant acceptance
  Q-->>D: Start driver matching
  R-->>O: Accept or reject order
  D-->>O: Assign available delivery partner
Diagram

If payment authorization fails, mark the order failed and do not dispatch it. If the restaurant rejects after authorization, cancel the order and issue a payment void/refund through a retryable compensation workflow. Delivery status is a state machine—ASSIGNED → PICKED_UP → DELIVERED—with validated actor permissions and durable events. For logout, revoke the refresh session and delete its Redis entry; use short-lived access tokens and check session revocation for sensitive operations to limit token reuse.

6. Scale, bottlenecks & trade-offs

  • Cache popular menus and restaurant search results, but use short TTLs and invalidate on menu changes; always recheck price and availability when ordering.
  • Replicate SQL for reads and use backups plus tested restore procedures. Keep order writes strongly consistent; accept slightly stale search and location reads.
  • Partition queues by order or region to preserve per-order event order. Make consumers idempotent, retry transient failures with backoff, and route poison messages to a dead-letter queue.
  • Dispatch can bottleneck during meal peaks. Match by distance, availability, and estimated pickup time; cap offer timeouts and rematch when a partner declines. Location updates should be throttled and expire when a partner disconnects.
  • This is a deliberate consistency trade-off: order/payment state favors correctness over availability, while discovery favors availability and cacheability. External payment and notification providers remain failure points, so use timeouts, circuit breakers, reconciliation jobs, and clear pending states rather than claiming success prematurely.
TechnicalEasyZohoSoftware Engineer

19. Why is Java considered an object-oriented language?

Model answer

Java is considered object-oriented because it organizes most application behavior around classes and objects. A class defines state and behavior; an object is a runtime instance of that class.

Its object-oriented features include:

  1. Encapsulation: Classes combine data and methods, and access modifiers such as private control how that state can be accessed.
  2. Abstraction: Interfaces and abstract classes expose useful contracts while hiding implementation details.
  3. Inheritance: A class can extend another class to reuse or specialize behavior.
  4. Polymorphism: A reference to a superclass or interface can refer to different implementations, whose overridden methods are selected at runtime.

For example, a Zoho application could define a NotificationSender interface with email and in-app implementations. Code that depends on the interface can use either implementation without needing to know its internal details.

A useful nuance: Java is not purely object-oriented. It has primitive types such as int and boolean, which are not objects, although wrapper classes such as Integer provide object forms. So the accurate description is that Java is a strongly object-oriented, class-based language with some non-object primitive types.

TechnicalEasyZohoSoftware Engineer

20. Why is Java considered platform-independent?

Model answer

Java is considered platform-independent because Java source code is compiled into bytecode, rather than directly into machine code for one operating system or processor. A compatible Java Virtual Machine (JVM) on each platform executes that bytecode.

flowchart LR
    S["Java source"] --> C["Java compiler"]
    C --> B["Platform-neutral bytecode"]
    B --> J1["JVM on Windows"]
    B --> J2["JVM on Linux"]
    B --> J3["JVM on macOS"]
Diagram

The usual summary is “write once, run anywhere”: compile the program once, then run the resulting bytecode on platforms with a compatible JVM. The JVM handles platform-specific execution, often using just-in-time compilation to convert frequently executed bytecode into native machine code.

This is not an absolute guarantee that every Java application runs unchanged everywhere. It can depend on the JVM version, operating-system-specific APIs, native libraries, filesystem assumptions, or other environmental requirements. For portable applications, developers should target compatible Java versions and avoid unnecessary platform-specific dependencies.

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