Wipro interview questions & answers

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

CodingEasyWiproSoftware Engineer

1. Merge Sorted Array (LeetCode)

Model answer

The task

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

Key idea

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

Approach

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

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

Complexity:

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

Common follow-ups

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

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

3. 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.
CodingEasyWiproSoftware Engineer

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

5. 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.
CodingEasyWiproSoftware Engineer

6. Add Strings (LeetCode)

Model answer

The task

Given two strings representing nonnegative integers, return their sum as a string. The solution should perform the addition directly on the digits rather than converting either entire string to an integer.

Key idea

Add digits from right to left, keeping a carry just as in manual addition. Since the strings can have different lengths, treat missing digits as zero.

Approach

  1. Start at the final digit of each string with a carry of zero.
  2. While either string has digits left or a carry remains, read the next digits (using zero if a string is exhausted).
  3. Add the digits and carry; append the result’s ones digit and update the carry.
  4. Reverse the collected digits to form the answer.
class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        i = len(num1) - 1
        j = len(num2) - 1
        carry = 0
        result = []

        while i >= 0 or j >= 0 or carry:
            digit1 = ord(num1[i]) - ord("0") if i >= 0 else 0
            digit2 = ord(num2[j]) - ord("0") if j >= 0 else 0

            total = digit1 + digit2 + carry
            result.append(str(total % 10))
            carry = total // 10

            i -= 1
            j -= 1

        return "".join(reversed(result))

Complexity:

  • Time: O(max(n, m)), where n and m are the input lengths.
  • Space: O(max(n, m)) for the output digits.

Common follow-ups

  • How would you subtract two nonnegative number strings? Compare magnitudes first, then subtract digits with borrowing.
  • How would you handle negative values? Parse and track each sign, then add or subtract magnitudes as appropriate.
  • How would you add many number strings? Accumulate them with this routine, or use a digit-wise accumulator for a single pass over all inputs.
CodingEasyWiproSoftware Engineer

7. Toeplitz Matrix (LeetCode)

Model answer

The task

Determine whether every diagonal running from the top-left to the bottom-right of a matrix contains the same value. The matrix is Toeplitz exactly when this holds for all such diagonals.

Key idea

Each cell that is not in the first row or first column shares a diagonal with the cell immediately above and to its left. Comparing each such pair checks every diagonal without storing extra values.

Approach

  1. Let the matrix dimensions be rows and cols.
  2. Visit each cell starting from row 1 and column 1.
  3. Compare its value with the value at (row - 1, col - 1).
  4. Return False as soon as a pair differs.
  5. If all pairs match, return True.
class Solution:
    def isToeplitzMatrix(self, matrix: list[list[int]]) -> bool:
        rows = len(matrix)
        cols = len(matrix[0])

        # Every non-edge cell must match the cell above-left.
        for row in range(1, rows):
            for col in range(1, cols):
                if matrix[row][col] != matrix[row - 1][col - 1]:
                    return False

        return True

Complexity:

  • Time: O(rows × cols), since each cell is checked at most once.
  • Space: O(1), since the algorithm uses only a few variables.

Common follow-ups

  • Can the matrix be checked as it is read? Yes, retain the previous row and compare each new row’s entries with the previous row shifted by one position.
  • What if the matrix is too large to fit in memory? Stream rows from storage and keep only the preceding row; this uses O(cols) extra space.
  • How can the check be parallelized? Each cell comparison is independent, so comparisons can be split across workers and their results combined.
CodingEasyWiproSoftware Engineer

8. Add Binary (LeetCode)

Model answer

The task

Given two strings representing binary numbers, return their sum as a binary string.

Key idea

Add digits from right to left, keeping a carry just as in ordinary column addition. This avoids converting potentially long strings to integers.

Approach

  1. Start at the last character of each string with a carry of zero.
  2. While either string has digits left or a carry remains, add the available digits and the carry.
  3. Append the sum’s low bit; use the remaining value as the next carry.
  4. Reverse the collected digits to produce the result.
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        i, j = len(a) - 1, len(b) - 1
        carry = 0
        result = []

        while i >= 0 or j >= 0 or carry:
            total = carry

            if i >= 0:
                total += int(a[i])
                i -= 1

            if j >= 0:
                total += int(b[j])
                j -= 1

            result.append(str(total % 2))
            carry = total // 2

        return "".join(reversed(result))

Complexity:

  • Time: O(max(n, m)), where n and m are the input lengths.
  • Space: O(max(n, m)) for the output digits.

Common follow-ups

  • How would you handle signed binary values? Define a representation such as two’s complement, then account for its fixed width.
  • Can you avoid converting each character to an integer? Subtract '0' from each character to obtain its digit.
  • What if the inputs contain leading zeroes? The addition still works; optionally normalize the returned string.
  • How would you add many binary strings? Repeatedly apply pairwise addition, or use a suitable multi-operand addition strategy.
CodingEasyWiproSoftware Engineer

9. Pascal's Triangle (LeetCode)

Model answer

The task

Given a number of rows, build Pascal’s Triangle up to that many rows. Each row starts and ends with 1, and each interior value is the sum of the two values above it.

Key idea

Construct rows from top to bottom. For each new row, use the previous row to compute its interior values.

Approach

  1. Start with an empty list of rows.
  2. For each row index, create a row of the required length filled with 1s.
  3. For interior positions, add the two relevant values from the preceding row.
  4. Append the completed row and return all rows.
from typing import List

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        triangle: List[List[int]] = []

        for row_index in range(numRows):
            # The first and last entries are always 1.
            row = [1] * (row_index + 1)

            # Compute interior entries from the previous row.
            if row_index > 1:
                previous = triangle[-1]
                for column in range(1, row_index):
                    row[column] = previous[column - 1] + previous[column]

            triangle.append(row)

        return triangle

Complexity:

  • Time: O(n²), since the total number of entries generated is proportional to the square of the number of rows.
  • Space: O(n²), to store the returned triangle.

Common follow-ups

  • Return only the row at a given index: build rows iteratively while retaining only the current row.
  • Generate a row using binomial coefficients: compute each value from the preceding value in constant time.
  • Reduce auxiliary space: update one row in place, working from right to left so earlier values remain available.
CodingEasyWiproSoftware Engineer

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

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

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

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

14. Max Consecutive Ones (LeetCode)

Model answer

The task

Given an array containing zeros and ones, return the length of its longest contiguous run of ones. A zero breaks a run.

Key idea

Scan once, tracking the current run of ones and the longest run seen so far. Reset the current run whenever a zero appears.

Approach

  1. Initialize the current run length and best length to zero.
  2. Visit each value in the array.
  3. If it is one, increase the current run and update the best length.
  4. Otherwise, reset the current run to zero.
  5. Return the best length.
from typing import List

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        current = 0
        longest = 0

        for value in nums:
            if value == 1:
                current += 1
                longest = max(longest, current)
            else:
                current = 0

        return longest

Complexity:

  • Time: O(n), where n is the number of array elements.
  • Space: O(1), since only two counters are used.

Common follow-ups

  • What if the array is empty? The algorithm returns zero.
  • What if one zero may be flipped? Track a sliding window containing at most one zero.
  • What if the input is streamed? Keep the same two counters and update them as each value arrives.
CodingEasyWiproSoftware Engineer

15. Kids With the Greatest Number of Candies (LeetCode)

Model answer

The task

For each child, decide whether giving them all the extra candies would let them tie or exceed the current maximum. Return the decisions in the same order as the children.

Key idea

Find the current maximum once. Then compare each child’s candy count plus the extra amount with that maximum.

Approach

  1. Compute the largest value in candies.
  2. For each count, check whether adding extraCandies reaches or passes that largest value.
  3. Return the resulting Boolean values.
from typing import List

class Solution:
    def kidsWithCandies(
        self, candies: List[int], extraCandies: int
    ) -> List[bool]:
        greatest = max(candies)
        return [count + extraCandies >= greatest for count in candies]

Complexity:

  • Time: O(n), where n is the number of children; finding the maximum and checking each count are both linear.
  • Space: O(n) for the returned list; the calculation uses O(1) additional space beyond that.

Common follow-ups

  • What if a child must strictly exceed the current maximum? Replace >= with >.
  • Can the decisions be produced without storing a list? Yield each comparison from a generator, using O(1) extra space.
CodingMediumWiproSoftware Engineer

16. 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.
CodingMediumWiproSoftware Engineer

17. Group Anagrams (LeetCode)

Model answer

The task

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

Key idea

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

Approach

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

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

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

        return list(groups.values())

Complexity:

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

Common follow-ups

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

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