Autocoder

Nagarro coding round questions

Last updated 2026-11-19

Nagarro is commonly described by candidates as setting a tougher coding bar than a typical services-company test: medium-level problems in which a brute force often will not pass the time limit. Nagarro has not published a syllabus we can cite, so this set is practice at that level: sliding window, intervals, dynamic programming, graphs and a design problem.

Each problem has worked Python and Java code, complexity and the common mistake. Expect to explain your approach as well as code it; see Nagarro interview questions.

Style (commonly reported)Medium problems, time limits that reject brute force
Difficulty hereMedium to hard
LanguagesPython and Java shown

How to approach harder problems

State the brute force and its complexity first, then ask which repeated work you can remove: a hash map, a sliding window, sorting, or memoisation. That habit is how you move from O(n^2) to O(n) and it is the thing interviewers want to hear.

Practise writing each solution twice: once to get it right, once under a timer. The DSA coding round guide describes a timing plan.

Hiring status

We hold no sourced Nagarro statement on fresher numbers or dates, so none are quoted here. Confirm the test pattern with Nagarro's own careers site and your invitation.

Nagarro coding round questions: questions with worked answers

  1. 1

    Find the length of the longest substring without repeating characters.

    medium

    Sliding window with a map. Sliding window with a map of the last index of each character. Move the left edge to one past the previous occurrence when a repeat falls inside the window. O(n) time, O(min(n, alphabet)) space. A frequent bug is moving the left edge backwards because the stale index of a repeated character lies outside the current window, so take the maximum.

    python
    def longest_unique(s):
        last, left, best = {}, 0, 0
        for i, ch in enumerate(s):
            if ch in last and last[ch] >= left:
                left = last[ch] + 1
            last[ch] = i
            best = max(best, i - left + 1)
        return best
    java
    import java.util.*;
    class Solution {
        static int longestUnique(String s) {
            Map<Character, Integer> last = new HashMap<>();
            int left = 0, best = 0;
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (last.containsKey(c) && last.get(c) >= left) left = last.get(c) + 1;
                last.put(c, i);
                best = Math.max(best, i - left + 1);
            }
            return best;
        }
    }
  2. 2

    Merge all overlapping intervals.

    medium

    Sorting and sweeping. Sort by start, then sweep: if the next interval starts at or before the end of the last merged one, extend the end with the maximum; otherwise start a new interval. Sorting dominates, so O(n log n) time and O(n) output space. Using the next end instead of max(end, next end) breaks cases where one interval is fully inside another.

    python
    def merge(intervals):
        intervals.sort()
        out = []
        for s, e in intervals:
            if out and s <= out[-1][1]:
                out[-1][1] = max(out[-1][1], e)
            else:
                out.append([s, e])
        return out
    java
    import java.util.*;
    class Solution {
        static int[][] merge(int[][] iv) {
            Arrays.sort(iv, (a, b) -> Integer.compare(a[0], b[0]));
            List<int[]> out = new ArrayList<>();
            for (int[] cur : iv) {
                if (!out.isEmpty() && cur[0] <= out.get(out.size() - 1)[1])
                    out.get(out.size() - 1)[1] = Math.max(out.get(out.size() - 1)[1], cur[1]);
                else out.add(new int[]{cur[0], cur[1]});
            }
            return out.toArray(new int[0][]);
        }
    }
  3. 3

    Find all unique triplets in an array that sum to zero.

    medium

    Two pointers with duplicate handling. Sort the array. Fix the first element, then use two pointers on the rest, moving them inward according to whether the sum is below or above zero. Skip duplicate values for the first element and after finding a triplet. O(n^2) time, O(1) extra space besides the output. Skipping duplicates incorrectly is where most solutions fail.

    python
    def three_sum(a):
        a.sort()
        res = []
        for i in range(len(a) - 2):
            if i and a[i] == a[i - 1]:
                continue
            l, r = i + 1, len(a) - 1
            while l < r:
                s = a[i] + a[l] + a[r]
                if s < 0:
                    l += 1
                elif s > 0:
                    r -= 1
                else:
                    res.append([a[i], a[l], a[r]])
                    l += 1
                    r -= 1
                    while l < r and a[l] == a[l - 1]:
                        l += 1
        return res
    java
    import java.util.*;
    class Solution {
        static List<List<Integer>> threeSum(int[] a) {
            Arrays.sort(a);
            List<List<Integer>> res = new ArrayList<>();
            for (int i = 0; i < a.length - 2; i++) {
                if (i > 0 && a[i] == a[i - 1]) continue;
                int l = i + 1, r = a.length - 1;
                while (l < r) {
                    int s = a[i] + a[l] + a[r];
                    if (s < 0) l++;
                    else if (s > 0) r--;
                    else {
                        res.add(Arrays.asList(a[i], a[l], a[r]));
                        l++; r--;
                        while (l < r && a[l] == a[l - 1]) l++;
                    }
                }
            }
            return res;
        }
    }
  4. 4

    Given bar heights, compute how much rain water is trapped between them.

    hard

    A hard two-pointer classic. Use two pointers with running left and right maxima. Move the pointer with the smaller height, because water above it is limited by that side maximum, and add max - height. O(n) time, O(1) space. Computing prefix and suffix maxima arrays is equivalent with O(n) space. Mixing up which side to move is the common bug.

    python
    def trap(h):
        l, r = 0, len(h) - 1
        lmax = rmax = water = 0
        while l < r:
            if h[l] < h[r]:
                lmax = max(lmax, h[l])
                water += lmax - h[l]
                l += 1
            else:
                rmax = max(rmax, h[r])
                water += rmax - h[r]
                r -= 1
        return water
    java
    class Solution {
        static int trap(int[] h) {
            int l = 0, r = h.length - 1, lmax = 0, rmax = 0, water = 0;
            while (l < r) {
                if (h[l] < h[r]) { lmax = Math.max(lmax, h[l]); water += lmax - h[l]; l++; }
                else { rmax = Math.max(rmax, h[r]); water += rmax - h[r]; r--; }
            }
            return water;
        }
    }
  5. 5

    Find the longest palindromic substring of a string.

    medium

    Expand around centre. Expand around each of the 2n - 1 centres (each character and each gap) while the ends match, keeping the best range. O(n^2) time, O(1) space, which is usually accepted. Manacher gives O(n) but is rarely expected. Forgetting the even-length centres misses answers such as "abba".

    python
    def longest_palindrome(s):
        best = ""
        for c in range(len(s)):
            for l, r in ((c, c), (c, c + 1)):
                while l >= 0 and r < len(s) and s[l] == s[r]:
                    l -= 1
                    r += 1
                if r - l - 1 > len(best):
                    best = s[l + 1:r]
        return best
    java
    class Solution {
        static String longestPalindrome(String s) {
            int start = 0, len = 0;
            for (int c = 0; c < s.length(); c++) {
                for (int k = 0; k < 2; k++) {
                    int l = c, r = c + k;
                    while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }
                    if (r - l - 1 > len) { len = r - l - 1; start = l + 1; }
                }
            }
            return s.substring(start, start + len);
        }
    }
  6. 6

    Find the fewest coins needed to make an amount, or -1 if impossible.

    medium

    Dynamic programming where greedy fails. Dynamic programming over amounts: dp[x] is the minimum of dp[x - c] + 1 over all coins c not exceeding x, with dp[0] = 0. O(amount * coins) time, O(amount) space. A greedy choice of the largest coin fails for sets such as {1, 3, 4} with amount 6, which is the point the interviewer is testing.

    python
    def coin_change(coins, amount):
        INF = amount + 1
        dp = [0] + [INF] * amount
        for x in range(1, amount + 1):
            for c in coins:
                if c <= x:
                    dp[x] = min(dp[x], dp[x - c] + 1)
        return dp[amount] if dp[amount] != INF else -1
    java
    import java.util.*;
    class Solution {
        static int coinChange(int[] coins, int amount) {
            int[] dp = new int[amount + 1];
            Arrays.fill(dp, amount + 1);
            dp[0] = 0;
            for (int x = 1; x <= amount; x++)
                for (int c : coins)
                    if (c <= x) dp[x] = Math.min(dp[x], dp[x - c] + 1);
            return dp[amount] > amount ? -1 : dp[amount];
        }
    }
  7. 7

    0/1 knapsack: given item weights, values and a capacity, find the maximum total value.

    hard

    Classic 0/1 knapsack. Let dp[w] be the best value with capacity w. For each item, iterate w from the capacity down to the item weight so each item is used at most once: dp[w] = max(dp[w], dp[w - wt] + val). O(n * W) time, O(W) space. Iterating upwards turns it into the unbounded knapsack, the most common error.

    python
    def knapsack(weights, values, cap):
        dp = [0] * (cap + 1)
        for wt, val in zip(weights, values):
            for w in range(cap, wt - 1, -1):
                dp[w] = max(dp[w], dp[w - wt] + val)
        return dp[cap]
    java
    class Solution {
        static int knapsack(int[] wt, int[] val, int cap) {
            int[] dp = new int[cap + 1];
            for (int i = 0; i < wt.length; i++)
                for (int w = cap; w >= wt[i]; w--)
                    dp[w] = Math.max(dp[w], dp[w - wt[i]] + val[i]);
            return dp[cap];
        }
    }
  8. 8

    Find the minimum number of insertions, deletions and replacements to turn one string into another.

    hard

    Two-dimensional dynamic programming. Edit distance by dynamic programming: dp[i][j] is the cost for the first i characters of a and first j of b. If the characters match it equals dp[i-1][j-1]; otherwise it is 1 plus the minimum of the replace, delete and insert cells. Base cases are i and j. O(mn) time; keep two rows to reduce space to O(n).

    python
    def edit_distance(a, b):
        m, n = len(a), len(b)
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(m + 1):
            dp[i][0] = i
        for j in range(n + 1):
            dp[0][j] = j
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if a[i - 1] == b[j - 1]:
                    dp[i][j] = dp[i - 1][j - 1]
                else:
                    dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1])
        return dp[m][n]
    java
    class Solution {
        static int editDistance(String a, String b) {
            int m = a.length(), n = b.length();
            int[][] dp = new int[m + 1][n + 1];
            for (int i = 0; i <= m; i++) dp[i][0] = i;
            for (int j = 0; j <= n; j++) dp[0][j] = j;
            for (int i = 1; i <= m; i++)
                for (int j = 1; j <= n; j++)
                    dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1) ? dp[i - 1][j - 1]
                        : 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1]));
            return dp[m][n];
        }
    }
  9. 9

    Design an LRU cache with O(1) get and put.

    medium

    Design with hash map plus ordering. Combine a hash map with a doubly linked list so lookups and recency updates are both O(1). In Python, OrderedDict with move_to_end does this; in Java, LinkedHashMap in access order with removeEldestEntry. Evict the least recently used entry when the size exceeds capacity. Forgetting that get must also refresh recency is the usual bug.

    python
    from collections import OrderedDict
    
    class LRUCache:
        def __init__(self, capacity):
            self.cap = capacity
            self.d = OrderedDict()
    
        def get(self, key):
            if key not in self.d:
                return -1
            self.d.move_to_end(key)
            return self.d[key]
    
        def put(self, key, value):
            self.d[key] = value
            self.d.move_to_end(key)
            if len(self.d) > self.cap:
                self.d.popitem(last=False)
    java
    import java.util.*;
    class LRUCache extends LinkedHashMap<Integer, Integer> {
        private final int cap;
        LRUCache(int cap) { super(16, 0.75f, true); this.cap = cap; }
        int fetch(int k) { return containsKey(k) ? get(k) : -1; }
        @Override protected boolean removeEldestEntry(Map.Entry<Integer, Integer> e) { return size() > cap; }
    }
  10. 10

    Count the islands in a grid of 1s (land) and 0s (water), where islands connect horizontally or vertically.

    medium

    Graph flood fill on a grid. Scan the grid; on each unvisited land cell, increment the count and flood-fill its component with DFS or BFS, marking cells visited. O(rows * cols) time and O(rows * cols) worst-case recursion space. Counting diagonal neighbours as connected, or forgetting to mark visited cells, gives wrong or infinite results.

    python
    def num_islands(grid):
        if not grid:
            return 0
        R, C = len(grid), len(grid[0])
        def dfs(r, c):
            if r < 0 or c < 0 or r >= R or c >= C or grid[r][c] != "1":
                return
            grid[r][c] = "0"
            dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1)
        count = 0
        for r in range(R):
            for c in range(C):
                if grid[r][c] == "1":
                    count += 1
                    dfs(r, c)
        return count
    java
    class Solution {
        static int numIslands(char[][] g) {
            int count = 0;
            for (int r = 0; r < g.length; r++)
                for (int c = 0; c < g[0].length; c++)
                    if (g[r][c] == '1') { count++; dfs(g, r, c); }
            return count;
        }
        static void dfs(char[][] g, int r, int c) {
            if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] != '1') return;
            g[r][c] = '0';
            dfs(g, r + 1, c); dfs(g, r - 1, c); dfs(g, r, c + 1); dfs(g, r, c - 1);
        }
    }
  11. 11

    Given courses and prerequisite pairs, decide whether all courses can be finished.

    hard

    Cycle detection with topological sort. This is cycle detection in a directed graph. Use Kahn algorithm: compute in-degrees, process nodes with zero in-degree, reduce their neighbours, and check that all courses were processed. O(V + E) time and space. If some nodes never reach zero in-degree, a cycle exists.

    python
    from collections import deque
    
    def can_finish(n, prereqs):
        adj = [[] for _ in range(n)]
        indeg = [0] * n
        for a, b in prereqs:
            adj[b].append(a)
            indeg[a] += 1
        q = deque(i for i in range(n) if indeg[i] == 0)
        done = 0
        while q:
            u = q.popleft()
            done += 1
            for v in adj[u]:
                indeg[v] -= 1
                if indeg[v] == 0:
                    q.append(v)
        return done == n
    java
    import java.util.*;
    class Solution {
        static boolean canFinish(int n, int[][] prereqs) {
            List<List<Integer>> adj = new ArrayList<>();
            for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
            int[] indeg = new int[n];
            for (int[] p : prereqs) { adj.get(p[1]).add(p[0]); indeg[p[0]]++; }
            Deque<Integer> q = new ArrayDeque<>();
            for (int i = 0; i < n; i++) if (indeg[i] == 0) q.add(i);
            int done = 0;
            while (!q.isEmpty()) {
                int u = q.poll();
                done++;
                for (int v : adj.get(u)) if (--indeg[v] == 0) q.add(v);
            }
            return done == n;
        }
    }
  12. 12

    Given a string and a dictionary of words, decide whether the string can be split into dictionary words.

    medium

    String dynamic programming. dp[i] is true if the prefix of length i can be segmented. For each i, check every j below i where dp[j] is true and s[j:i] is in the dictionary. O(n^2) substring checks with a hash set. Plain recursion without memoisation is exponential on strings like "aaaa...ab".

    python
    def word_break(s, words):
        ws = set(words)
        dp = [True] + [False] * len(s)
        for i in range(1, len(s) + 1):
            for j in range(i):
                if dp[j] and s[j:i] in ws:
                    dp[i] = True
                    break
        return dp[len(s)]
    java
    import java.util.*;
    class Solution {
        static boolean wordBreak(String s, List<String> words) {
            Set<String> ws = new HashSet<>(words);
            boolean[] dp = new boolean[s.length() + 1];
            dp[0] = true;
            for (int i = 1; i <= s.length(); i++)
                for (int j = 0; j < i; j++)
                    if (dp[j] && ws.contains(s.substring(j, i))) { dp[i] = true; break; }
            return dp[s.length()];
        }
    }

Frequently asked questions

How hard is the Nagarro coding test?

Candidates commonly describe medium-level problems. Prepare beyond easy array questions.

Is dynamic programming required?

Basic dynamic programming such as coin change and knapsack is worth practising for harder tests.

Python or Java?

Use the language you can write correctly under time pressure.

How should I split my practice time?

Mostly medium problems on arrays, strings, trees, hashing and graphs, with a few harder ones.

Where is the official format?

In your Nagarro invitation and on its careers site.

Related guides

More in Company Interview Questions

See all in this section