Autocoder

Cognizant Coding Round Questions with Solutions

Last updated 2026-11-19

Cognizant's coding round is commonly reported to be a bug-fixing format as well as a writing one. This page practises both: four problems in the style of fixing planted errors, and six short writing problems, all with Python and Java solutions.

Use it with Cognizant interview questions and how to crack the Cognizant interview.

FormatOften AMCAT Automata Fix (bug-fixing), per prep sources
LanguagesPython and Java shown
LevelEasy to medium

What the Cognizant coding round looks like

Prep sources describe Cognizant's coding round as often being AMCAT's Automata Fix: you are given code with planted errors and must correct them so it passes test cases, rather than write a program from nothing. Not every cycle uses it, so confirm from your own instructions. The first four problems below are written in that bug-fixing spirit, each naming the typical planted mistake, and the rest are the short writing problems that commonly sit beside it. They are practice in the style of the topic, not a recorded paper.

How to approach bug-fixing questions

Cognizant Coding Round Questions with Solutions: questions with worked answers

  1. 1

    Fix the bug: sum of digits

    easy

    The buggy version loops while n > 0 but never reduces n, so it runs forever. The fix is n //= 10 inside the loop. Bug-fixing questions usually have exactly one or two planted errors, so read each line for the loop update, the condition and the return. Complexity: O(d) time for d digits, O(1) space. Common mistakes: fixing the symptom by adding a break instead of updating the loop variable.

    python
    def digit_sum(n):
        s = 0
        while n > 0:
            s += n % 10
            n //= 10   # missing in the buggy version
        return s
    print(digit_sum(4821))  # 15
    java
    class Solution {
        static int digitSum(int n) {
            int s = 0;
            while (n > 0) {
                s += n % 10;
                n /= 10;   // missing in the buggy version
            }
            return s;
        }
    }
  2. 2

    Fix the bug: binary search that never ends

    medium

    A common planted bug is lo = mid or hi = mid, which can loop forever when lo + 1 == hi. Use lo = mid + 1 and hi = mid - 1 with the condition lo <= hi, and compute mid as lo + (hi - lo) / 2. Complexity: O(log n) time, O(1) space. Common mistakes: mixing the inclusive and exclusive bound styles within one function.

    python
    def bsearch(a, t):
        lo, hi = 0, len(a) - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            if a[mid] == t: return mid
            if a[mid] < t: lo = mid + 1
            else: hi = mid - 1
        return -1
    print(bsearch([1, 3, 5, 7, 9], 7), bsearch([1, 3], 4))  # 3 -1
    java
    class Solution {
        static int bsearch(int[] a, int t) {
            int lo = 0, hi = a.length - 1;
            while (lo <= hi) {
                int mid = lo + (hi - lo) / 2;
                if (a[mid] == t) return mid;
                if (a[mid] < t) lo = mid + 1; else hi = mid - 1;
            }
            return -1;
        }
    }
  3. 3

    Fix the bug: maximum of an array with negative numbers

    easy

    The buggy version starts max at 0, so an all-negative array returns 0. Initialise with the first element (or minus infinity) and loop from the second element. Complexity: O(n) time, O(1) space. Common mistakes: initialising with 0 or a magic constant such as -9999.

    python
    def array_max(a):
        m = a[0]
        for x in a[1:]:
            if x > m: m = x
        return m
    print(array_max([-8, -3, -12]))  # -3
    java
    class Solution {
        static int arrayMax(int[] a) {
            int m = a[0];
            for (int i = 1; i < a.length; i++) if (a[i] > m) m = a[i];
            return m;
        }
    }
  4. 4

    Fix the bug: factorial that overflows or starts at zero

    medium

    Two planted bugs are typical: a loop starting at 0 (multiplying everything by zero) and using int, which overflows past 12!. Start the loop at 2 and use long (20! fits in a signed 64-bit integer) or BigInteger for more. Python integers do not overflow. Complexity: O(n) time, O(1) space. Common mistakes: starting the product at 0 and forgetting that 0! is 1.

    python
    def fact(n):
        r = 1
        for i in range(2, n + 1): r *= i
        return r
    print(fact(0), fact(5), fact(20))  # 1 120 2432902008176640000
    java
    class Solution {
        static long fact(int n) {
            long r = 1;
            for (int i = 2; i <= n; i++) r *= i;
            return r;
        }
    }
  5. 5

    Count vowels and consonants in a string

    easy

    Loop through characters; for letters (check isalpha) increment the vowel count if the lower-cased character is in aeiou, otherwise the consonant count. Ignore digits, spaces and punctuation. Complexity: O(n) time, O(1) space. Common mistakes: counting spaces and digits as consonants, and forgetting uppercase vowels.

    python
    def count_vc(s):
        v = c = 0
        for ch in s.lower():
            if ch.isalpha():
                if ch in "aeiou": v += 1
                else: c += 1
        return v, c
    print(count_vc("Hello World"))  # (3, 7)
    java
    class Solution {
        static int[] countVc(String s) {
            int v = 0, c = 0;
            for (char ch : s.toLowerCase().toCharArray()) {
                if (!Character.isLetter(ch)) continue;
                if ("aeiou".indexOf(ch) >= 0) v++; else c++;
            }
            return new int[]{v, c};
        }
    }
  6. 6

    Sum of both diagonals of a square matrix

    easy

    The primary diagonal has cells (i, i) and the secondary has (i, n - 1 - i). When n is odd the centre cell lies on both, so subtract it once if you want a combined sum without double counting. Complexity: O(n) time, O(1) space. Common mistakes: double counting the centre cell and using a nested loop with O(n squared) work.

    python
    def diag_sums(m):
        n = len(m)
        p = sum(m[i][i] for i in range(n))
        s = sum(m[i][n - 1 - i] for i in range(n))
        return p, s
    print(diag_sums([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))  # (15, 15)
    java
    class Solution {
        static int[] diagSums(int[][] m) {
            int p = 0, s = 0, n = m.length;
            for (int i = 0; i < n; i++) { p += m[i][i]; s += m[i][n - 1 - i]; }
            return new int[]{p, s};
        }
    }
  7. 7

    Second smallest element

    medium

    Track smallest and second smallest in one pass, updating the second only for values strictly greater than the smallest and smaller than the current second. Return a sentinel when all elements are equal. Complexity: O(n) time, O(1) space. Common mistakes: sorting and taking index 1 (wrong with duplicates) and not handling arrays shorter than two.

    python
    def second_smallest(a):
        lo = sec = float('inf')
        for x in a:
            if x < lo: lo, sec = x, lo
            elif lo < x < sec: sec = x
        return None if sec == float('inf') else sec
    print(second_smallest([4, 2, 2, 7, 3]))  # 3
    java
    class Solution {
        static long secondSmallest(int[] a) {
            long lo = Long.MAX_VALUE, sec = Long.MAX_VALUE;
            for (int x : a) {
                if (x < lo) { sec = lo; lo = x; }
                else if (x > lo && x < sec) sec = x;
            }
            return sec == Long.MAX_VALUE ? -1 : sec;
        }
    }
  8. 8

    Check whether a number is a perfect number

    medium

    A perfect number equals the sum of its proper divisors (6 = 1 + 2 + 3). Loop i up to the square root, adding both i and n / i for each divisor pair, and exclude n itself. Complexity: O(sqrt n) time, O(1) space. Common mistakes: counting n as its own divisor, double adding i when i * i == n, and treating 1 as perfect.

    python
    def is_perfect(n):
        if n < 2: return False
        s = 1
        i = 2
        while i * i <= n:
            if n % i == 0:
                s += i
                if i != n // i: s += n // i
            i += 1
        return s == n
    print([x for x in range(1, 500) if is_perfect(x)])  # [6, 28, 496]
    java
    class Solution {
        static boolean isPerfect(int n) {
            if (n < 2) return false;
            int s = 1;
            for (int i = 2; (long) i * i <= n; i++) {
                if (n % i == 0) { s += i; if (i != n / i) s += n / i; }
            }
            return s == n;
        }
    }
  9. 9

    Sort elements by frequency, then by value

    medium

    Count occurrences, then sort the distinct values by descending frequency with ties broken by ascending value, and expand them. Use a custom comparator or a key tuple. Complexity: O(n log n) time, O(n) space. Common mistakes: sorting by frequency only, which leaves ties in arbitrary order, and not expanding values back to their counts.

    python
    from collections import Counter
    def sort_by_freq(a):
        c = Counter(a)
        return sorted(a, key=lambda x: (-c[x], x))
    print(sort_by_freq([4, 5, 6, 5, 4, 3]))  # [4, 4, 5, 5, 3, 6]
    java
    import java.util.*;
    class Solution {
        static List<Integer> sortByFreq(int[] a) {
            Map<Integer, Integer> c = new HashMap<>();
            for (int x : a) c.merge(x, 1, Integer::sum);
            List<Integer> out = new ArrayList<>();
            for (int x : a) out.add(x);
            out.sort((x, y) -> !c.get(x).equals(c.get(y)) ? c.get(y) - c.get(x) : x - y);
            return out;
        }
    }
  10. 10

    Find the longest word in a sentence

    easy

    Split the sentence on whitespace, strip punctuation from each word, and keep the first word with the greatest length. Decide and state how ties are broken (first occurrence here). Complexity: O(n) time, O(n) space. Common mistakes: counting punctuation in the length and replacing on ties when the first is required.

    python
    import re
    def longest_word(s):
        best = ""
        for w in re.findall(r"[A-Za-z0-9']+", s):
            if len(w) > len(best): best = w
        return best
    print(longest_word("Fix the longest-running service bug"))  # longest
    java
    class Solution {
        static String longestWord(String s) {
            String best = "";
            for (String w : s.split("[^A-Za-z0-9']+"))
                if (w.length() > best.length()) best = w;
            return best;
        }
    }

Frequently asked questions

Is the Cognizant coding round only bug fixing?

Prep sources say it is often Automata Fix but cycles differ. Check your instructions.

Which language should I practise?

Whichever the test offers that you know best; Java, Python and C++ are typical.

Can I rewrite the code from scratch?

In fix-style questions, small targeted edits are safer than rewriting, as the grader runs test cases against expected behaviour.

How do I prepare quickly?

Practise tracing code by hand and learn the common planted bugs: loop updates, bounds, initial values and operators.

Sources

Related guides

More in Company Interview Questions

See all in this section