Tata Consultancy Services interview questions & answers

20 real Tata Consultancy Services interview questions with full model answers — Technical, Coding. Drawn from the same verified bank ChannelPulse drills from (270 Tata Consultancy Services questions in total).

CodingEasyTata Consultancy ServicesSoftware Engineer

1. Subtree of Another Tree (LeetCode)

Model answer

The task

Determine whether one binary tree occurs in another as a subtree: both the node values and the tree structure must match.

Key idea

Serialize each tree in preorder, recording a marker for every missing child. These markers preserve structure, so the smaller tree is a subtree exactly when its serialization appears contiguously in the larger tree’s serialization. Use KMP to search in linear time.

Approach

  1. Treat an empty candidate tree as a subtree.
  2. Serialize each tree in preorder, using None to represent missing nodes.
  3. Build the KMP prefix table for the candidate serialization.
  4. Scan the larger serialization with KMP and return whether the candidate is found.
class Solution:
    def isSubtree(self, root, subRoot):
        if subRoot is None:
            return True

        def serialize(node):
            tokens = []

            def visit(current):
                if current is None:
                    tokens.append(None)
                    return

                tokens.append(current.val)
                visit(current.left)
                visit(current.right)

            visit(node)
            return tokens

        text = serialize(root)
        pattern = serialize(subRoot)

        # Build the KMP prefix table.
        prefix = [0] * len(pattern)
        matched = 0

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

            if pattern[i] == pattern[matched]:
                matched += 1
                prefix[i] = matched

        # Search for the candidate serialization.
        matched = 0
        for token in text:
            while matched and token != pattern[matched]:
                matched = prefix[matched - 1]

            if token == pattern[matched]:
                matched += 1
                if matched == len(pattern):
                    return True

        return False

Complexity:

  • Time: O(n + m), where n and m are the numbers of nodes in the two trees.
  • Space: O(n + m) for the serialized tokens and KMP prefix table.

Common follow-ups

  • Can this be done without serialization? Try matching the candidate at every node; the worst case is O(nm).
  • What if many subtree queries use the same main tree? Cache a structural hash for each node, then verify matches to guard against collisions.
  • How do you avoid recursion-depth issues on skewed trees? Serialize iteratively with an explicit stack.
CodingEasyTata Consultancy ServicesSoftware Engineer

2. 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.
CodingEasyTata Consultancy ServicesSoftware Engineer

3. Set Mismatch (LeetCode)

Model answer

The task

An array contains values from 1 through its length, except one value appears twice and another is absent. Return the repeated value and the missing value, in that order.

Key idea

XOR all array values with all values in the expected range. Matching values cancel, leaving the XOR of the duplicate and missing values. Split the values by a distinguishing bit to recover both candidates, then count one candidate to determine which is repeated.

Approach

  1. XOR each array value and each expected value together.
  2. Find a set bit in the resulting XOR; the two answers differ at that bit.
  3. XOR values in each group separately to get the two candidates.
  4. Count one candidate in the array to identify the duplicate and return the result.
class Solution:
    def findErrorNums(self, nums: list[int]) -> list[int]:
        n = len(nums)
        combined_xor = 0

        # Equal values cancel, leaving duplicate XOR missing.
        for expected, value in enumerate(nums, start=1):
            combined_xor ^= expected ^ value

        # The lowest set bit separates the two candidates.
        distinguishing_bit = combined_xor & -combined_xor
        candidate_a = 0
        candidate_b = 0

        for expected, value in enumerate(nums, start=1):
            if value & distinguishing_bit:
                candidate_a ^= value
            else:
                candidate_b ^= value

            if expected & distinguishing_bit:
                candidate_a ^= expected
            else:
                candidate_b ^= expected

        # Exactly one candidate occurs twice in nums.
        if sum(value == candidate_a for value in nums) == 2:
            return [candidate_a, candidate_b]
        return [candidate_b, candidate_a]

Complexity:

  • Time: O(n), using a constant number of linear passes.
  • Space: O(1), storing only a fixed number of variables.

Common follow-ups

  • What if the input may contain more than one error? This XOR partition relies on exactly one duplicate and one missing value.
  • Can you use a hash set? Yes; track seen values to find the duplicate, then scan 1..n for the missing value, using O(n) extra space.
  • Can the input be modified? Sign marking can find both values in O(n) time and O(1) extra space, but it changes the array unless restored.
CodingEasyTata Consultancy ServicesSoftware Engineer

4. Flood Fill (LeetCode)

Model answer

The task

Given a grid of pixel colors and a starting cell, recolor the starting cell and every cell connected to it up, down, left, or right that has the same original color. Return the updated grid.

Key idea

Explore the connected region using DFS, recoloring cells as they are visited. The recoloring also marks cells as visited, so they are not processed again. If the requested color is already the starting cell’s color, return immediately to avoid revisiting cells.

Approach

  1. Save the starting cell’s original color.
  2. If it already matches the new color, return the grid unchanged.
  3. Initialize a stack with the starting coordinates.
  4. Pop cells, recolor them, and add any in-bounds neighbors that still have the original color.
  5. Return the modified grid.
class Solution:
    def floodFill(
        self,
        image: list[list[int]],
        sr: int,
        sc: int,
        color: int
    ) -> list[list[int]]:
        rows, cols = len(image), len(image[0])
        original = image[sr][sc]

        # Without this check, recolored cells would still match the original.
        if original == color:
            return image

        stack = [(sr, sc)]
        image[sr][sc] = color

        while stack:
            row, col = stack.pop()

            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nr, nc = row + dr, col + dc

                if (
                    0 <= nr < rows
                    and 0 <= nc < cols
                    and image[nr][nc] == original
                ):
                    # Recolor immediately so this cell is added only once.
                    image[nr][nc] = color
                    stack.append((nr, nc))

        return image

Complexity:

  • Time: O(mn) in the worst case, where every cell belongs to the connected region.
  • Space: O(mn) in the worst case for the DFS stack.

Common follow-ups

  • What if the region should connect diagonally too? Check all eight surrounding neighbors instead of four.
  • Can this be done with BFS? Yes; use a queue in place of the stack.
  • What if the grid is very large? Consider iterative traversal to avoid recursion-depth limits.
  • What if the input grid must remain unchanged? Copy it first and perform the traversal on the copy.
CodingEasyTata Consultancy ServicesSoftware Engineer

5. Palindrome Linked List (LeetCode)

Model answer

The task

Determine whether a singly linked list reads the same from front to back and back to front. Return a boolean without relying on access to nodes by index.

Key idea

Find the midpoint with slow and fast pointers, then reverse the second half. Compare the two halves node by node; reverse the second half again afterward to restore the original list.

Approach

  1. Advance slow by one node and fast by two until fast reaches the end.
  2. For an odd-length list, move the start of the second half past the middle node.
  3. Reverse the second half in place.
  4. Compare corresponding values from the head and reversed second half.
  5. Restore the second half before returning the result.
class Solution:
    def isPalindrome(self, head):
        def reverse(node):
            previous = None
            while node:
                following = node.next
                node.next = previous
                previous = node
                node = following
            return previous

        slow = fast = head

        # Find the midpoint. For odd length, fast ends on the final node.
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

        # Skip the middle node when the list has odd length.
        second_half_start = slow.next if fast else slow
        reversed_half = reverse(second_half_start)

        # Compare the first half with the reversed second half.
        left = head
        right = reversed_half
        is_palindrome = True

        while right:
            if left.val != right.val:
                is_palindrome = False
                break
            left = left.next
            right = right.next

        # Restore the list to its original structure.
        reverse(reversed_half)
        return is_palindrome

Complexity:

  • Time: O(n), to find the midpoint, reverse, compare, and restore.
  • Space: O(1), using only a few pointers.

Common follow-ups

  • What if the list must not be modified, even temporarily? Use a stack to store values, which takes O(n) extra space.
  • How can recursion solve it? Recursively compare nodes from the ends, using O(n) call-stack space.
  • What about empty or single-node lists? Both are palindromes; the code handles them directly.
CodingEasyTata Consultancy ServicesSoftware Engineer

6. 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.
CodingEasyTata Consultancy ServicesSoftware Engineer

7. Maximum Product of Three Numbers (LeetCode)

Model answer

The task

Given an integer array with at least three values, return the largest product obtainable by choosing any three values.

Key idea

The maximum product is either the product of the three largest values, or the largest value multiplied by the two smallest values. The second case matters because multiplying two large-magnitude negative values produces a positive result.

Approach

  1. Scan the array once, tracking its three largest values.
  2. During the same scan, track its two smallest values.
  3. Calculate the product of the three largest values.
  4. Calculate the product of the largest value and two smallest values.
  5. Return the larger product.
class Solution:
    def maximumProduct(self, nums: list[int]) -> int:
        largest = second_largest = third_largest = float("-inf")
        smallest = second_smallest = float("inf")

        for value in nums:
            # Maintain the three largest values.
            if value >= largest:
                largest, second_largest, third_largest = (
                    value,
                    largest,
                    second_largest,
                )
            elif value >= second_largest:
                second_largest, third_largest = value, second_largest
            elif value > third_largest:
                third_largest = value

            # Maintain the two smallest values.
            if value <= smallest:
                smallest, second_smallest = value, smallest
            elif value < second_smallest:
                second_smallest = value

        largest_three_product = largest * second_largest * third_largest
        two_smallest_product = largest * smallest * second_smallest

        return max(largest_three_product, two_smallest_product)

Complexity:

  • Time: O(n), for one pass through the array.
  • Space: O(1), using a fixed number of variables.

Common follow-ups

  • What if the array has fewer than three values? Define the desired behavior, such as rejecting the input.
  • Can the input contain duplicate values? Yes; the comparisons deliberately allow duplicates.
  • How would you return the chosen values as well as the product? Track the values associated with the winning candidate.
CodingEasyTata Consultancy ServicesSoftware Engineer

8. Binary Tree Inorder Traversal (LeetCode)

Model answer

The task

Return the values of a binary tree’s nodes in inorder: visit the left subtree, then the current node, then the right subtree. The result should preserve that visit order in a list.

Key idea

An explicit stack lets us simulate recursive inorder traversal without using the call stack. Keep moving left while saving nodes; after visiting a saved node, continue into its right subtree.

Approach

  1. Initialize an empty result list, an empty stack, and set the current node to the root.
  2. While there is a current node or the stack is nonempty, push the current node and move left.
  3. When there is no current node, pop the most recently saved node and append its value.
  4. Set the current node to the popped node’s right child and continue.
  5. Return the result after all nodes have been visited.
# The platform provides the TreeNode class.
class Solution:
    def inorderTraversal(self, root):
        result = []
        stack = []
        current = root

        while current is not None or stack:
            # Save the path down the left side.
            while current is not None:
                stack.append(current)
                current = current.left

            # Visit the next node, then explore its right subtree.
            current = stack.pop()
            result.append(current.val)
            current = current.right

        return result

Complexity:

  • Time: O(n), since each node is pushed, popped, and visited once.
  • Space: O(h), where h is the tree height; the stack holds at most one root-to-leaf path.

Common follow-ups

  • Can this be implemented recursively? Yes; recursively traverse the left child, visit the node, then traverse the right child.
  • What is the worst-case auxiliary space? O(n) for a completely skewed tree; a balanced tree uses O(log n).
  • Can the traversal use constant extra space? Morris traversal achieves O(1) auxiliary space by temporarily modifying and restoring tree links.
  • How would you produce preorder or postorder instead? Change the visit order; postorder may require a second stack or a modified iterative traversal.
CodingEasyTata Consultancy ServicesSoftware Engineer

9. 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.
CodingEasyTata Consultancy ServicesSoftware Engineer

10. 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.
CodingEasyTata Consultancy ServicesSoftware Engineer

11. Reshape the Matrix (LeetCode)

Model answer

The task

Rearrange a matrix’s elements in row-major order into a matrix with the requested dimensions. If the new dimensions cannot hold exactly the same number of elements, return the original matrix unchanged.

Key idea

Reshaping changes where elements are placed, not their order. The element at flat index k belongs at row k // c and column k % c in the reshaped matrix.

Approach

  1. Read the original row and column counts.
  2. If the requested shape has a different total number of cells, return the original matrix.
  3. Create an empty result with the requested number of rows.
  4. Visit source elements in row-major order, tracking their flat index.
  5. Place each element at the corresponding destination row and column.
from typing import List

class Solution:
    def matrixReshape(
        self, mat: List[List[int]], r: int, c: int
    ) -> List[List[int]]:
        # Handle an empty matrix safely.
        if not mat or not mat[0]:
            return mat if r * c == 0 else mat

        rows, cols = len(mat), len(mat[0])

        # A reshape is possible only if the element counts match.
        if rows * cols != r * c:
            return mat

        result = [[0] * c for _ in range(r)]

        # Map each source element's row-major index to its new position.
        for i in range(rows):
            for j in range(cols):
                index = i * cols + j
                result[index // c][index % c] = mat[i][j]

        return result

Complexity:

  • Time: O(mn), where m × n is the original matrix size; each element is visited once.
  • Space: O(mn) for the reshaped result.

Common follow-ups

  • What if the requested dimensions do not match the element count? Return the original matrix without changing it.
  • Can the reshape be done without allocating another matrix? Only if modifying storage in place is allowed; the mapping is more involved.
  • How would you support a stream of elements? Buffer elements until a full destination row is available, then emit that row.
CodingEasyTata Consultancy ServicesSoftware Engineer

12. Next Greater Element I (LeetCode)

Model answer

The task

For each value in one array, find the first larger value appearing to its right in a second array that contains it. Return -1 when no such value exists.

Key idea

Scan the second array from left to right with a decreasing stack. When a new value is larger than values on the stack, it is the next greater value for each of them; store those answers in a hash map.

Approach

  1. Initialize an empty stack and a map of answers.
  2. For each value in the second array, pop smaller values from the stack and map each popped value to the current value.
  3. Push the current value onto the stack.
  4. Values still on the stack have no greater value to their right.
  5. Build the result by looking up each value from the first array, using -1 when it has no mapped answer.
from typing import List

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        next_greater = {}
        decreasing_stack = []

        for value in nums2:
            # The current value is the first greater value for each
            # smaller value waiting on the stack.
            while decreasing_stack and decreasing_stack[-1] < value:
                next_greater[decreasing_stack.pop()] = value
            decreasing_stack.append(value)

        # Any value without a recorded answer has no greater value to its right.
        return [next_greater.get(value, -1) for value in nums1]

Complexity:

  • Time: O(n + m), where n and m are the lengths of the two arrays; each value is pushed and popped at most once.
  • Space: O(m), for the stack and answer map.

Common follow-ups

  • What if the second array is circular? Scan it twice, using indices modulo its length, and push only during the first pass.
  • What if values can repeat? Track indices on the stack and define how to match repeated values from the first array.
  • Can the answers be found online as values arrive? Yes; resolve stack entries when a larger value arrives, while retaining unresolved entries.
CodingEasyTata Consultancy ServicesSoftware Engineer

13. Balanced Binary Tree (LeetCode)

Model answer

The task

Determine whether a binary tree is height-balanced: at every node, the heights of its left and right subtrees must differ by at most one.

Key idea

Compute subtree heights with a postorder depth-first search. Return a sentinel value as soon as a subtree is unbalanced, so the search can stop early instead of repeatedly computing heights.

Approach

  1. Define a recursive helper that returns a subtree’s height, or -1 if it is unbalanced.
  2. Treat an empty subtree as height 0.
  3. Check the left subtree; propagate -1 immediately if it is unbalanced.
  4. Check the right subtree and propagate -1 if needed.
  5. If the two heights differ by more than one, return -1; otherwise return their height plus one.
  6. The tree is balanced exactly when the helper returns something other than -1.
from typing import Optional

# TreeNode is provided by the judge.
class Solution:
    def isBalanced(self, root: Optional["TreeNode"]) -> bool:
        def height(node: Optional["TreeNode"]) -> int:
            if node is None:
                return 0

            left_height = height(node.left)
            if left_height == -1:
                return -1

            right_height = height(node.right)
            if right_height == -1:
                return -1

            if abs(left_height - right_height) > 1:
                return -1

            return 1 + max(left_height, right_height)

        return height(root) != -1

Complexity:

  • Time: O(n), where n is the number of nodes; each node is visited at most once.
  • Space: O(h), where h is the tree height, for the recursion stack.

Common follow-ups

  • What if the tree is extremely deep? Use an iterative postorder traversal to avoid recursion-stack limits.
  • How can the height be computed without the sentinel? Return both a height and a balance flag from each recursive call.
  • Can this also report the first unbalanced node? Return that node along with the failure signal, propagating it upward.
CodingEasyTata Consultancy ServicesSoftware Engineer

14. 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.
TechnicalEasyTata Consultancy ServicesSoftware EngineerTechnical Interview

15. What is object-oriented programming (OOP)?

Model answer

Object-oriented programming (OOP) is a way to structure software around objects: units that combine state (data) with behavior (methods). Objects are created from classes or similar constructs and interact through defined interfaces.

The main OOP concepts are:

  • Encapsulation: Keep an object’s state and the operations that manage it together, while controlling access to that state.
  • Abstraction: Expose the essential operations and hide unnecessary implementation details.
  • Inheritance: Reuse or extend behavior from a parent type where the relationship is genuinely appropriate.
  • Polymorphism: Let different types respond to the same operation in their own way, such as different payment methods implementing pay().

For example, in an enterprise application, an Invoice object might hold line items and expose calculateTotal(). Callers use that operation without needing to know how taxes or discounts are calculated. OOP can improve modularity and maintainability, but I would use it where object boundaries reflect the domain rather than forcing every piece of logic into a class.

TechnicalEasyTata Consultancy ServicesSoftware EngineerTechnical Interview

16. How can you apply encapsulation?

Model answer

I apply encapsulation by making state private and exposing only operations that preserve the object’s rules. For example:

class BankAccount {
  #balance;

  constructor(initialBalance = 0) {
    if (initialBalance < 0) {
      throw new Error("Initial balance cannot be negative");
    }
    this.#balance = initialBalance;
  }

  deposit(amount) {
    if (amount <= 0) {
      throw new Error("Deposit must be positive");
    }
    this.#balance += amount;
  }

  withdraw(amount) {
    if (amount <= 0 || amount > this.#balance) {
      throw new Error("Invalid withdrawal");
    }
    this.#balance -= amount;
  }

  getBalance() {
    return this.#balance;
  }
}
  • Keep fields private or otherwise inaccessible to callers.
  • Provide meaningful methods for allowed operations, and validate inputs there.
  • Avoid exposing mutable internal objects directly; return a copy or read-only view when needed.
  • Keep the public interface small so implementation changes do not ripple through callers.
TechnicalEasyTata Consultancy ServicesSoftware EngineerTechnical Interview

17. What is the difference between data abstraction and encapsulation?

Model answer

Abstraction and encapsulation are related, but they answer different questions:

  • Abstraction — what can I do? It presents the essential operations of a component while hiding details that callers do not need. For example, a payment interface may expose pay(amount) without revealing how a card provider processes the payment.
  • Encapsulation — how is the state protected? It restricts direct access to internal data and allows changes through controlled operations. A payment implementation might keep credentials private and validate payment state internally.

In short, abstraction simplifies what a caller sees; encapsulation protects how the implementation and its state are managed. A well-designed class often uses both: a small public interface and private implementation details.

TechnicalEasyTata Consultancy ServicesSoftware EngineerTechnical Interview

18. What is encapsulation?

Model answer

Encapsulation means keeping an object’s data and the operations that act on it together, while restricting direct access to its internal state.

Instead of allowing callers to change a bank account’s balance arbitrarily, the account can provide operations such as deposit() and withdraw(). Those methods validate the request and preserve rules—for example, rejecting a withdrawal that would make the balance negative.

Encapsulation helps protect invariants, reduces accidental misuse, and allows the implementation to change without requiring callers to change. It is more than simply putting fields and methods in the same class: the object should control how its state is accessed and modified.

TechnicalEasyTata Consultancy ServicesSoftware EngineerTechnical Interview

19. What are classes and objects?

Model answer

  • A class is a blueprint that defines the data and behavior objects of a type can have. In Java, it might define fields such as name and methods such as introduce().
  • An object is a particular instance of that class, created with its own field values. For example, employee1 and employee2 can both be Employee objects but have different names.
  • Classes help organize code; objects let the program work with individual entities. This is a core idea in object-oriented programming.
TechnicalMediumTata Consultancy ServicesSoftware EngineerTechnical Interview

20. Can you name three companies that are using the latest technologies?

Model answer

Three examples I’d give are Microsoft, NVIDIA, and Amazon. Microsoft is investing in generative AI and cloud services through Azure; NVIDIA develops accelerated-computing platforms used for AI workloads; and Amazon applies machine learning and generative AI across AWS and its retail operations. These are examples of companies actively working with current technologies, rather than a claim that any one company uses every “latest” technology. In a TCS project, I’d choose technologies based on the client’s needs, security requirements, and measurable business value—not novelty alone.

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