Nagarro interview questions & answers

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

CodingEasyNagarroSoftware Engineer

1. Smallest Pair With Different Frequencies (LeetCode)

Model answer

The task

The title suggests finding a pair of array values whose frequencies differ, then choosing the smallest such pair. The metadata does not specify what “smallest” means, so the code below leaves the pair-ranking rule to the caller.

Key idea

Count each value once, then compare distinct values using their counts. A ranking function lets the caller define “smallest” without assuming whether that means lexicographic order, minimum difference, or something else.

Approach

  1. Build a frequency table for the array.
  2. Sort the distinct values so each unordered pair is considered once.
  3. Skip pairs whose frequencies are equal.
  4. Keep the eligible pair with the lowest caller-provided ranking.
from collections import Counter
from collections.abc import Callable, Hashable, Sequence
from typing import TypeVar

T = TypeVar("T", bound=Hashable)

def smallest_pair_with_different_frequencies(
    values: Sequence[T],
    pair_rank: Callable[[tuple[T, T]], object],
) -> tuple[T, T] | None:
    """Return the lowest-ranked value pair with unequal frequencies.

    Each pair is ordered by value. The caller supplies the ranking rule.
    """
    counts = Counter(values)
    distinct = sorted(counts)

    best_pair = None
    best_rank = None

    for i, first in enumerate(distinct):
        for second in distinct[i + 1:]:
            if counts[first] == counts[second]:
                continue

            pair = (first, second)
            rank = pair_rank(pair)

            if best_pair is None or rank < best_rank:
                best_pair = pair
                best_rank = rank

    return best_pair

Complexity:

  • Time: O(n + u²), where n is the array length and u is the number of distinct values.
  • Space: O(u) for the frequency table.

Common follow-ups

  • What does “smallest” mean? Specify whether to rank by values, difference, indices, or another rule.
  • Should pairs use values or array positions? That changes which pairs are considered.
  • Can the search be faster? It may be, once the exact ranking rule is defined.
  • What if no valid pair exists? Return None, or use the required problem-specific result.
CodingEasyNagarroSoftware Engineer

2. Implement Stack using Queues (LeetCode)

Model answer

The task

Build a last-in, first-out stack using queue operations. Support adding an item, removing and inspecting the most recently added item, and checking whether the stack is empty.

Key idea

Keep the newest item at the front of a single queue. After each insertion, rotate the earlier items behind it; this makes removal and inspection constant time.

Approach

  1. Store items in a deque, using it as a queue.
  2. On push, append the new item to the back.
  3. Rotate the previous items to the back so the new item becomes the front.
  4. Implement pop and top using the front of the queue.
  5. The queue is empty exactly when the stack is empty.
from collections import deque

class MyStack:
    def __init__(self):
        self._queue = deque()

    def push(self, x: int) -> None:
        # Put the new item first, then move older items behind it.
        self._queue.append(x)
        for _ in range(len(self._queue) - 1):
            self._queue.append(self._queue.popleft())

    def pop(self) -> int:
        return self._queue.popleft()

    def top(self) -> int:
        return self._queue[0]

    def empty(self) -> bool:
        return not self._queue

Complexity:

  • Time: push is O(n) due to rotation; pop, top, and empty are O(1).
  • Space: O(n) for the stored items.

Common follow-ups

  • Can push be O(1) instead? Yes: use two queues and transfer items during pop, making pop O(n).
  • What if the queue only exposes enqueue and dequeue? The same rotation uses only those operations.
  • How should empty pop or top behave? Follow the API contract; if calls are not guaranteed valid, raise an exception or return a designated sentinel.
CodingEasyNagarroSoftware Engineer

3. Linked List Cycle (LeetCode)

Model answer

The task

Determine whether a singly linked list eventually revisits a node, forming a cycle.

Key idea

Move two pointers through the list at different speeds. If a cycle exists, the faster pointer eventually catches the slower one; if the fast pointer reaches the end, the list is acyclic.

Approach

  1. Initialize both pointers at the list head.
  2. Advance the slow pointer by one node and the fast pointer by two.
  3. If the fast pointer or its next node is None, return False.
  4. If the pointers meet, return True.
from typing import Optional

class Solution:
    def hasCycle(self, head: Optional["ListNode"]) -> bool:
        # The slow pointer moves one step at a time.
        slow = head
        # The fast pointer moves two steps at a time.
        fast = head

        while fast is not None and fast.next is not None:
            slow = slow.next
            fast = fast.next.next

            if slow is fast:
                return True

        return False

Complexity:

  • Time: O(n), where n is the number of nodes visited before the pointers meet or the list ends.
  • Space: O(1), because only two pointers are used.

Common follow-ups

  • How could you solve it using a hash set? Record visited node identities; a repeated identity means there is a cycle, using O(n) extra space.
  • How can you find the cycle’s starting node? After the pointers meet, reset one to the head and move both one step at a time; their next meeting is the start.
  • How can you find the cycle’s length? Keep one pointer at the meeting node and advance another until it returns, counting steps.
CodingEasyNagarroSoftware Engineer

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

5. Using a Robot to Print the Lexicographically Smallest String (LeetCode)

Model answer

The task

Reorder a string using a robot that can move characters from the input into a holding area and emit characters from that area. Choose when to emit so the final string is lexicographically smallest.

Key idea

Keep the holding area as a stack and track the smallest character still unread. Emit from the stack whenever its top is no greater than that smallest unread character: waiting cannot produce a better next character.

Approach

  1. Count how many times each lowercase letter appears in the input.
  2. Scan the input from left to right, pushing each character onto the stack and updating its remaining count.
  3. Advance a pointer to the smallest letter that still appears in the unread suffix.
  4. While the stack top is no greater than that letter, pop it into the result.
  5. Once the input is exhausted, emit everything left in the stack.
class Solution:
    def robotWithString(self, s: str) -> str:
        # Count characters that have not yet been read.
        remaining = [0] * 26
        for ch in s:
            remaining[ord(ch) - ord("a")] += 1

        stack = []
        result = []
        smallest = 0

        for ch in s:
            stack.append(ch)

            # This character is now in the stack, not the unread suffix.
            remaining[ord(ch) - ord("a")] -= 1

            while smallest < 26 and remaining[smallest] == 0:
                smallest += 1

            # No unread character can improve on the stack's top.
            while stack and (
                smallest == 26
                or stack[-1] <= chr(ord("a") + smallest)
            ):
                result.append(stack.pop())

        return "".join(result)

Complexity:

  • Time: O(n + Σ), where n is the string length and Σ is the alphabet size.
  • Space: O(n + Σ) for the stack, result, and character counts.

Common follow-ups

  • What if the alphabet is not fixed? Use a frequency map and an ordered structure to track the smallest remaining character.
  • Can the input be processed as a stream? Yes, if characters arrive in order; keep the stack, counts for available input, and result state.
  • Why is the comparison inclusive? If the stack top equals the smallest unread character, emitting it now is just as good as waiting, so it can be safely emitted.
CodingMediumNagarroSoftware Engineer

6. Sort Colors (LeetCode)

Model answer

The task

Rearrange an array containing only 0, 1, and 2 so the values appear in ascending order. Modify the array in place.

Key idea

Use three pointers to divide the array into regions: 0s at the front, 2s at the back, and 1s in between. Each step places one value into its correct region, so the array is processed in one pass without extra storage.

Approach

  1. Set low to the start and high to the end of the array.
  2. Scan with current, starting at the beginning.
  3. If the current value is 0, swap it with low, then advance both pointers.
  4. If it is 1, advance current.
  5. If it is 2, swap it with high and move high left. Do not advance current, since the swapped-in value still needs inspection.
  6. Stop when current passes high.
class Solution:
    def sortColors(self, nums: list[int]) -> None:
        """Sort nums in place; return no value."""
        low = 0
        current = 0
        high = len(nums) - 1

        while current <= high:
            if nums[current] == 0:
                nums[low], nums[current] = nums[current], nums[low]
                low += 1
                current += 1
            elif nums[current] == 1:
                current += 1
            else:  # nums[current] == 2
                nums[current], nums[high] = nums[high], nums[current]
                high -= 1

Complexity:

  • Time: O(n), where n is the number of values; each pointer moves only across the array.
  • Space: O(1), since the rearrangement is in place.

Common follow-ups

  • What if there are k distinct values? Use counting or a generalized partitioning strategy; the best approach depends on whether extra passes or storage are allowed.
  • Must the sort be stable? This in-place partitioning is not stable; preserving the order of equal values may require extra space or a different algorithm.
  • What if values outside 0, 1, and 2 appear? Validate or define their placement, then adapt the partitioning logic accordingly.
CodingMediumNagarroSoftware Engineer

7. Count Number of Ways to Place Houses (LeetCode)

Model answer

The task

Count the valid ways to place houses along both sides of a street with n plots per side. On either side, houses in neighboring plots cannot both be placed; empty plots are allowed.

Key idea

The choices for the two sides are independent. For one side, let ways(k) count arrangements across k plots: the last plot is either empty, or contains a house preceded by an empty plot, giving the Fibonacci-style recurrence ways(k) = ways(k - 1) + ways(k - 2).

Approach

  1. Count arrangements for one side, starting with ways(0) = 1 and ways(1) = 2.
  2. Iterate from plot 2 through plot n, keeping only the previous two counts.
  3. Square the one-side count to combine the independent choices for both sides.
  4. Apply the required modulo to the result.
class Solution:
    def countHousePlacements(self, n: int) -> int:
        mod = 1_000_000_007

        # Number of valid arrangements for zero and one plot.
        two_back = 1
        one_back = 2

        for _ in range(2, n + 1):
            current = (one_back + two_back) % mod
            two_back, one_back = one_back, current

        # The two sides can be chosen independently.
        return (one_back * one_back) % mod

Complexity:

  • Time: O(n), iterating once over the plots.
  • Space: O(1), storing only two previous counts.

Common follow-ups

  • How would you return the count for just one side? Return one_back before squaring.
  • Can the recurrence be evaluated faster for very large n? Use matrix exponentiation or fast doubling to compute the Fibonacci-style count in O(log n).
  • What changes if houses must be separated by at least d empty plots? Track the corresponding wider recurrence, or use a DP state that records the recent placement history.
CodingMediumNagarroSoftware Engineer

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