Autocoder

Coforge Coding Round Questions with Solutions

Last updated 2026-11-19

These ten medium-level problems practise the patterns that IT services tests with a coding section commonly use, with worked Python and Java solutions, complexity and mistakes. Coforge has not published its test content, so this is practice rather than a claimed paper.

Use it with Coforge interview questions and how to crack the DSA coding round.

LevelEasy to hard, mostly medium
LanguagesPython and Java shown
TopicsWindows, prefix sums, DP, greedy, recursion

What these Coforge-style problems cover

Coforge does not publish its test content, so we do not claim any specific paper. These ten problems are medium-level practice for IT services tests that include coding: sliding windows with maps, prefix sums with modulo, in-place index tricks, grid and string DP, greedy reachability and linked-list or tree recursion. They are the sort of problem used to confirm that a candidate who has done Java projects can also reason about algorithms.

Study plan for these ten

Coforge Coding Round Questions with Solutions: questions with worked answers

  1. 1

    Longest substring with at most K distinct characters

    medium

    Sliding window with a character count map. Expand the right edge; while the map has more than K keys, shrink from the left, deleting keys whose count reaches zero. Track the longest window. Complexity: O(n) time, O(K) space. Common mistakes: shrinking only once per step (use a while loop) and forgetting to delete zero-count keys, which keeps the distinct count wrong.

    python
    def longest_k(s, k):
        cnt, l, best = {}, 0, 0
        for r, c in enumerate(s):
            cnt[c] = cnt.get(c, 0) + 1
            while len(cnt) > k:
                cnt[s[l]] -= 1
                if cnt[s[l]] == 0: del cnt[s[l]]
                l += 1
            best = max(best, r - l + 1)
        return best
    print(longest_k("eceba", 2))  # 3
    java
    import java.util.*;
    class Solution {
        static int longestK(String s, int k) {
            Map<Character, Integer> cnt = new HashMap<>();
            int l = 0, best = 0;
            for (int r = 0; r < s.length(); r++) {
                cnt.merge(s.charAt(r), 1, Integer::sum);
                while (cnt.size() > k) {
                    char c = s.charAt(l++);
                    if (cnt.merge(c, -1, Integer::sum) == 0) cnt.remove(c);
                }
                best = Math.max(best, r - l + 1);
            }
            return best;
        }
    }
  2. 2

    Subarrays whose sum is divisible by K

    medium

    Prefix sums modulo K: two prefixes with the same remainder bound a subarray whose sum is divisible by K. Count pairs using a frequency map, normalising negative remainders. Complexity: O(n) time, O(K) space. Common mistakes: using a negative remainder (Java and C keep the sign) and forgetting the initial remainder 0 with count 1.

    python
    def sub_div_k(a, k):
        cnt, pre, res = {0: 1}, 0, 0
        for x in a:
            pre = (pre + x) % k
            res += cnt.get(pre, 0)
            cnt[pre] = cnt.get(pre, 0) + 1
        return res
    print(sub_div_k([4, 5, 0, -2, -3, 1], 5))  # 7
    java
    import java.util.*;
    class Solution {
        static int subDivK(int[] a, int k) {
            Map<Integer, Integer> cnt = new HashMap<>();
            cnt.put(0, 1);
            int pre = 0, res = 0;
            for (int x : a) {
                pre = ((pre + x) % k + k) % k;
                res += cnt.getOrDefault(pre, 0);
                cnt.merge(pre, 1, Integer::sum);
            }
            return res;
        }
    }
  3. 3

    First missing positive

    hard

    Place each value v in 1..n at index v - 1 by swapping, then the first index i where a[i] != i + 1 gives the answer i + 1. This is in place and linear because each swap puts one value in its final position. Complexity: O(n) time, O(1) space. Common mistakes: using a set (extra space) when O(1) is required and looping forever on duplicates (guard with a[a[i] - 1] != a[i]).

    python
    def first_missing(a):
        n = len(a)
        for i in range(n):
            while 1 <= a[i] <= n and a[a[i] - 1] != a[i]:
                j = a[i] - 1
                a[i], a[j] = a[j], a[i]
        for i in range(n):
            if a[i] != i + 1: return i + 1
        return n + 1
    print(first_missing([3, 4, -1, 1]), first_missing([1, 2, 0]))  # 2 3
    java
    class Solution {
        static int firstMissing(int[] a) {
            int n = a.length;
            for (int i = 0; i < n; i++)
                while (a[i] >= 1 && a[i] <= n && a[a[i] - 1] != a[i]) {
                    int j = a[i] - 1, t = a[i];
                    a[i] = a[j]; a[j] = t;
                }
            for (int i = 0; i < n; i++) if (a[i] != i + 1) return i + 1;
            return n + 1;
        }
    }
  4. 4

    Reverse a linked list in groups of k

    hard

    Reverse k nodes at a time, linking the reversed group to the result of the recursive call on the remainder. If fewer than k nodes remain, leave them as they are. Complexity: O(n) time, O(n / k) recursion. Common mistakes: reversing a trailing short group and losing the link between groups.

    python
    class Node:
        def __init__(self, v, nxt=None): self.v, self.next = v, nxt
    def reverse_k(head, k):
        probe = head
        for _ in range(k):
            if not probe: return head
            probe = probe.next
        prev, cur = reverse_k(probe, k), head
        for _ in range(k):
            cur.next, prev, cur = prev, cur, cur.next
        return prev
    h = reverse_k(Node(1, Node(2, Node(3, Node(4, Node(5))))), 2)
    out = []
    while h: out.append(h.v); h = h.next
    print(out)  # [2, 1, 4, 3, 5]
    java
    class Solution {
        static class Node { int v; Node next; Node(int v) { this.v = v; } }
        static Node reverseK(Node head, int k) {
            Node probe = head;
            for (int i = 0; i < k; i++) {
                if (probe == null) return head;
                probe = probe.next;
            }
            Node prev = reverseK(probe, k), cur = head;
            for (int i = 0; i < k; i++) {
                Node nxt = cur.next;
                cur.next = prev; prev = cur; cur = nxt;
            }
            return prev;
        }
    }
  5. 5

    Valid palindrome after deleting at most one character

    easy

    Two pointers inward; on the first mismatch, check whether the string is a palindrome after skipping either the left or the right character. Complexity: O(n) time, O(1) space. Common mistakes: trying to delete in many places (O(n squared)) and allowing more than one deletion.

    python
    def valid_pal2(s):
        def ok(i, j):
            while i < j:
                if s[i] != s[j]: return False
                i += 1; j -= 1
            return True
        i, j = 0, len(s) - 1
        while i < j:
            if s[i] != s[j]: return ok(i + 1, j) or ok(i, j - 1)
            i += 1; j -= 1
        return True
    print(valid_pal2("abca"), valid_pal2("abc"))  # True False
    java
    class Solution {
        static boolean ok(String s, int i, int j) {
            while (i < j) if (s.charAt(i++) != s.charAt(j--)) return false;
            return true;
        }
        static boolean validPal2(String s) {
            int i = 0, j = s.length() - 1;
            while (i < j) {
                if (s.charAt(i) != s.charAt(j)) return ok(s, i + 1, j) || ok(s, i, j - 1);
                i++; j--;
            }
            return true;
        }
    }
  6. 6

    Jump game: can you reach the last index?

    medium

    Greedy: track the farthest reachable index. If the current index exceeds it, you are stuck; if farthest reaches the last index, return true. Complexity: O(n) time, O(1) space. Common mistakes: using DP with O(n squared) checks and not stopping when the current index is unreachable.

    python
    def can_jump(a):
        far = 0
        for i, x in enumerate(a):
            if i > far: return False
            far = max(far, i + x)
        return True
    print(can_jump([2, 3, 1, 1, 4]), can_jump([3, 2, 1, 0, 4]))  # True False
    java
    class Solution {
        static boolean canJump(int[] a) {
            int far = 0;
            for (int i = 0; i < a.length; i++) {
                if (i > far) return false;
                far = Math.max(far, i + a[i]);
            }
            return true;
        }
    }
  7. 7

    Minimum path sum in a grid (moves right or down)

    medium

    dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]). A single row array is enough: update left to right. Complexity: O(m * n) time, O(n) space. Common mistakes: initialising the first row and column incorrectly (they have one way in) and mixing up rows and columns.

    python
    def min_path(g):
        R, C = len(g), len(g[0])
        dp = [float('inf')] * C; dp[0] = 0
        for i in range(R):
            for j in range(C):
                if j > 0: dp[j] = min(dp[j], dp[j - 1])
                dp[j] += g[i][j]
        return dp[-1]
    print(min_path([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))  # 7
    java
    import java.util.*;
    class Solution {
        static int minPath(int[][] g) {
            int R = g.length, C = g[0].length;
            int[] dp = new int[C];
            Arrays.fill(dp, Integer.MAX_VALUE);
            dp[0] = 0;
            for (int i = 0; i < R; i++)
                for (int j = 0; j < C; j++) {
                    if (j > 0) dp[j] = Math.min(dp[j], dp[j - 1]);
                    dp[j] += g[i][j];
                }
            return dp[C - 1];
        }
    }
  8. 8

    Decode ways: count the ways to decode a digit string

    medium

    dp over the string: a single digit 1-9 adds dp[i-1]; a two-digit number 10-26 adds dp[i-2]. A zero can only be part of 10 or 20. Complexity: O(n) time, O(1) space with two variables. Common mistakes: treating 0 as a valid single digit and forgetting that strings starting with 0 have zero ways.

    python
    def num_decodings(s):
        if not s or s[0] == '0': return 0
        prev2, prev1 = 1, 1
        for i in range(1, len(s)):
            cur = 0
            if s[i] != '0': cur += prev1
            if 10 <= int(s[i - 1:i + 1]) <= 26: cur += prev2
            prev2, prev1 = prev1, cur
        return prev1
    print(num_decodings("226"), num_decodings("06"))  # 3 0
    java
    class Solution {
        static int numDecodings(String s) {
            if (s.isEmpty() || s.charAt(0) == '0') return 0;
            int prev2 = 1, prev1 = 1;
            for (int i = 1; i < s.length(); i++) {
                int cur = 0;
                if (s.charAt(i) != '0') cur += prev1;
                int two = Integer.parseInt(s.substring(i - 1, i + 1));
                if (two >= 10 && two <= 26) cur += prev2;
                prev2 = prev1; prev1 = cur;
            }
            return prev1;
        }
    }
  9. 9

    Are two binary trees identical?

    easy

    Recursively compare: both null is equal, one null is not, and otherwise values must match and both subtrees must be identical. Complexity: O(n) time, O(h) space. Common mistakes: checking values only and not shapes, so trees with different structure compare equal.

    python
    class T:
        def __init__(self, v, l=None, r=None): self.v, self.l, self.r = v, l, r
    def same(a, b):
        if not a and not b: return True
        if not a or not b or a.v != b.v: return False
        return same(a.l, b.l) and same(a.r, b.r)
    print(same(T(1, T(2), T(3)), T(1, T(2), T(3))), same(T(1, T(2)), T(1, None, T(2))))  # True False
    java
    class Solution {
        static class T { int v; T l, r; T(int v) { this.v = v; } }
        static boolean same(T a, T b) {
            if (a == null && b == null) return true;
            if (a == null || b == null || a.v != b.v) return false;
            return same(a.l, b.l) && same(a.r, b.r);
        }
    }
  10. 10

    Intersection of three sorted arrays

    easy

    Advance three pointers: if all three values match, record it and move all; otherwise advance the pointer at the smallest value. Complexity: O(a + b + c) time, O(1) extra space. Common mistakes: using nested loops (cubic) and advancing the wrong pointer.

    python
    def common3(a, b, c):
        i = j = k = 0; out = []
        while i < len(a) and j < len(b) and k < len(c):
            if a[i] == b[j] == c[k]:
                out.append(a[i]); i += 1; j += 1; k += 1
            else:
                m = min(a[i], b[j], c[k])
                if a[i] == m: i += 1
                elif b[j] == m: j += 1
                else: k += 1
        return out
    print(common3([1, 2, 3, 4, 5], [1, 2, 5, 7, 9], [1, 3, 4, 5, 8]))  # [1, 5]
    java
    import java.util.*;
    class Solution {
        static List<Integer> common3(int[] a, int[] b, int[] c) {
            List<Integer> out = new ArrayList<>();
            int i = 0, j = 0, k = 0;
            while (i < a.length && j < b.length && k < c.length) {
                if (a[i] == b[j] && b[j] == c[k]) { out.add(a[i]); i++; j++; k++; }
                else {
                    int m = Math.min(a[i], Math.min(b[j], c[k]));
                    if (a[i] == m) i++; else if (b[j] == m) j++; else k++;
                }
            }
            return out;
        }
    }

Frequently asked questions

How hard is the Coforge coding test?

It is not published. Prep material for similar firms suggests easy to medium, with an occasional harder item.

Which topics should I prioritise?

Arrays, strings, hashing, windows, basic DP and linked lists.

Python or Java?

Use the one you know better; both are shown here.

Where can I see openings?

On Coforge's own careers site.

Related guides

More in Company Interview Questions

See all in this section