🪔 Diwali offer: from ₹99 till 8 NovSee prices →

Cognizant GenC coding questions (2026): practice problems with solutions

Updated 17 October 2026

Eight practice problems in the style of the coding questions students report from Cognizant's GenC hiring: strings, counting with a hash map, stacks, greedy choices and two "fix the logic" problems. Each one has the idea in plain words, a tested solution in Python, C++ and Java, and its time and space complexity.

We wrote every problem ourselves to match the common question types, so these aren't official Cognizant questions. Problems 7 and 8 show the traps that "fix the logic" questions are built on. Use them to learn the patterns, then take the real test on your own.

The problems

  1. The first letter that appears only onceStrings · Counting · Easy
  2. The best-selling itemHashing · Counting · Easy
  3. Longest stretch with no repeated letterStrings · Hashing · Sliding window · Medium
  4. Are the brackets balanced?Strings · Stack · Medium
  5. Fewest boats across the riverGreedy · Two pointers · Sorting · Medium
  6. Buy once, sell onceArrays · Greedy · Easy
  7. Where does the line go out of order?Arrays · Easy
  8. How many scored above the average?Arrays · Maths · Easy

What Cognizant's own pages say

GenC is Cognizant's hiring and development programme for new graduates in India. Its campus pages for the 2027 batch were up when we checked.

TrackFor
2027 on-campus hiring (GenC Next, GenC Pro and GenC)B.E., B.Tech, M.E. or M.Tech students, except Leather, Food and Fashion Technology and dual-degree students
AI and Analytics (2027)B.E. or B.Tech in AI and Data Science or AI and ML, or CSE or IT with an AI elective or honours
Analyst Trainee (2026 batch)Three-year degrees such as BCA, B.Sc, BA, B.Com, BBA and B.Voc
Ace Team Program (2027)Joins as full-stack AI engineers; its assessments cover full-stack AI development, data structures and algorithms, prompt engineering, retrieval-augmented generation, agentic AI and modern front-end development

Sources: Cognizant's GenC programme page, its campus pages for 2027 on-campus hiring, AI and Analytics and Analyst Trainee, and its Ace Team announcement. Checked on 17 October 2026.

How to practise with this page

1The first letter that appears only once

StringsCountingEasy

Given a word, find the first letter, reading from the left, that appears exactly once in the whole word. If every letter appears more than once, print -1.

Input
One word of 1 to 105 small letters.
Output
The letter, or -1.

Example 1 input

swiss

Output

w

Example 2 input

aabbcc

Output

-1

In swiss, s appears three times, while w and i appear once each, and w comes first. In aabbcc, every letter appears twice.

Approach

Counting each letter by scanning the whole word again takes O(N²) steps in the worst case. Instead, make two passes. First, count every letter with 26 counters. Then walk through the word again from the left and stop at the first letter whose count is 1.

The second pass must follow the word, not the alphabet: going from a to z would give i for swiss instead of w.

Solution

Python
import sys
from collections import Counter

word = sys.stdin.readline().strip()

count = Counter(word)        # how many times each letter appears
answer = "-1"
for ch in word:              # the first letter, from the left, that appears once
    if count[ch] == 1:
        answer = ch
        break
print(answer)
C++
#include <iostream>
#include <string>
using namespace std;

int main() {
    string word;
    cin >> word;

    int count[26] = {0};   // how many times each letter appears
    for (char c : word) count[c - 'a']++;

    for (char c : word) {  // the first letter, from the left, that appears once
        if (count[c - 'a'] == 1) {
            cout << c << '\n';
            return 0;
        }
    }
    cout << -1 << '\n';
}
Java
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String word = br.readLine().trim();

        int[] count = new int[26];   // how many times each letter appears
        for (char c : word.toCharArray()) count[c - 'a']++;

        for (char c : word.toCharArray()) {   // the first letter, from the left, that appears once
            if (count[c - 'a'] == 1) {
                System.out.println(c);
                return;
            }
        }
        System.out.println(-1);
    }
}

Time: O(N) · Extra space: O(1): just 26 counters

2The best-selling item

HashingCountingEasy

A shop's bill book lists the item code of each of its N sales. Find the item that was sold the most times. If several items are tied, choose the one with the smallest code. Print the code and how many times it was sold.

Input
N (1 ≤ N ≤ 105), then N item codes, each from 1 to 109.
Output
Two numbers: the item code and the number of times it was sold.

Example input

8
42 7 42 13 7 42 13 7

Output

7 3

42 and 7 were both sold three times, and 13 twice. 7 is the smaller of the two tied codes.

Approach

The codes go up to 109, so an array with one counter for every possible code would be far too big. Use a hash map from each code to its count (Counter in Python, unordered_map in C++, HashMap in Java) and add 1 for every sale.

Then look at every code in the map once. A code wins if it has more sales than the best so far, or the same number of sales and a smaller code. A hash map gives its codes back in no fixed order, which is why the tie needs this check.

Solution

Python
import sys
from collections import Counter

data = list(map(int, sys.stdin.read().split()))
n, codes = data[0], data[1:]

count = Counter(codes[:n])                         # code -> times sold
best = min(count, key=lambda c: (-count[c], c))    # most sales first, then the smaller code
print(best, count[best])
C++
#include <iostream>
#include <unordered_map>
using namespace std;

int main() {
    int n;
    cin >> n;
    unordered_map<int, int> count;   // code -> times sold
    for (int i = 0; i < n; i++) {
        int code;
        cin >> code;
        count[code]++;
    }

    int best = 0, bestCount = 0;
    for (auto &[code, times] : count) {
        // more sales wins; on a tie, the smaller code wins
        if (times > bestCount || (times == bestCount && code < best)) {
            best = code;
            bestCount = times;
        }
    }
    cout << best << ' ' << bestCount << '\n';
}
Java
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Map<Integer, Integer> count = new HashMap<>();   // code -> times sold
        for (int i = 0; i < n; i++) count.merge(sc.nextInt(), 1, Integer::sum);

        int best = 0, bestCount = 0;
        for (Map.Entry<Integer, Integer> e : count.entrySet()) {
            int code = e.getKey(), times = e.getValue();
            // more sales wins; on a tie, the smaller code wins
            if (times > bestCount || (times == bestCount && code < best)) {
                best = code;
                bestCount = times;
            }
        }
        System.out.println(best + " " + bestCount);
    }
}

Time: O(N) on average · Extra space: O(K), where K is the number of different codes

3Longest stretch with no repeated letter

StringsHashingSliding windowMedium

Given a word, find the length of the longest stretch of letters in a row in which no letter appears twice.

Input
One word of 1 to 105 small letters.
Output
The length of the longest such stretch.

Example 1 input

interview

Output

6

Example 2 input

aaaa

Output

1

ntervi has six different letters, and every longer stretch repeats a letter (i or e). In aaaa, every stretch longer than one letter repeats a.

Approach

Checking every stretch takes O(N²) steps or more. Instead, slide a window along the word. The window runs from start to the current letter and never holds a letter twice. Keep last, the position where each letter was last seen.

When the next letter was last seen inside the window (at or after start), move start to just after that earlier copy: the smallest move that removes the repeat. Then record the letter's new position and compare the window's length with the best so far. start only ever moves forward, so the whole thing is one pass.

Solution

Python
import sys

s = sys.stdin.readline().strip()

last = {}             # letter -> the position where we last saw it
start = best = 0      # the current stretch runs from start to i
for i, ch in enumerate(s):
    if last.get(ch, -1) >= start:   # ch is already inside the stretch,
        start = last[ch] + 1        # so begin just after its earlier copy
    last[ch] = i
    best = max(best, i - start + 1)
print(best)
C++
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s;
    cin >> s;

    int last[26];                  // letter -> the position where we last saw it
    fill(last, last + 26, -1);
    int start = 0, best = 0;       // the current stretch runs from start to i
    for (int i = 0; i < (int)s.size(); i++) {
        int c = s[i] - 'a';
        if (last[c] >= start)      // this letter is already inside the stretch,
            start = last[c] + 1;   // so begin just after its earlier copy
        last[c] = i;
        best = max(best, i - start + 1);
    }
    cout << best << '\n';
}
Java
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s = br.readLine().trim();

        int[] last = new int[26];      // letter -> the position where we last saw it
        Arrays.fill(last, -1);
        int start = 0, best = 0;       // the current stretch runs from start to i
        for (int i = 0; i < s.length(); i++) {
            int c = s.charAt(i) - 'a';
            if (last[c] >= start)      // this letter is already inside the stretch,
                start = last[c] + 1;   // so begin just after its earlier copy
            last[c] = i;
            best = Math.max(best, i - start + 1);
        }
        System.out.println(best);
    }
}

Time: O(N) · Extra space: O(1): one position for each of the 26 letters

4Are the brackets balanced?

StringsStackMedium

A line of code uses three kinds of brackets: (), [] and {}. The brackets are balanced if every opening bracket is closed later by a bracket of the same kind, and the bracket opened most recently is always the first one closed. Ignore every other character; a line with no brackets at all is balanced. Print YES if the brackets are balanced and NO if they aren't.

Input
One line of 1 to 105 characters: brackets, letters, digits, spaces and other symbols.
Output
YES or NO.

Example 1 input

if (a[i] > 0) { x = (y + 1); }

Output

YES

Example 2 input

{[(])}

Output

NO

In the second line, the ( is opened after the [, so it must be closed first, but a ] comes first.

Approach

Use a stack: a pile where you only add to and take from the top. When you see an opening bracket, put it on the stack. When you see a closing bracket, the top of the stack must be the matching opening bracket, and you take it off. If the stack is empty, or the top is a different kind, the answer is NO straight away.

At the end the stack must also be empty: anything left on it was opened and never closed, as in ((()). Counting the brackets isn't enough, because )( has one of each but isn't balanced.

Solution

Python
import sys

line = sys.stdin.readline()
opener = {")": "(", "]": "[", "}": "{"}   # each closing bracket and its opening partner

stack = []          # brackets opened but not closed yet
balanced = True
for ch in line:
    if ch in "([{":
        stack.append(ch)
    elif ch in opener:
        if not stack or stack[-1] != opener[ch]:
            balanced = False                # nothing to close, or the wrong kind
            break
        stack.pop()
print("YES" if balanced and not stack else "NO")   # anything left open is also wrong
C++
#include <iostream>
#include <string>
using namespace std;

int main() {
    string line;
    getline(cin, line);

    string stack;   // brackets opened but not closed yet
    bool balanced = true;
    for (char c : line) {
        if (c == '(' || c == '[' || c == '{') {
            stack.push_back(c);
        } else if (c == ')' || c == ']' || c == '}') {
            char want = c == ')' ? '(' : c == ']' ? '[' : '{';
            if (stack.empty() || stack.back() != want) {
                balanced = false;   // nothing to close, or the wrong kind
                break;
            }
            stack.pop_back();
        }
    }
    cout << (balanced && stack.empty() ? "YES" : "NO") << '\n';   // anything left open is also wrong
}
Java
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();
        if (line == null) line = "";

        char[] stack = new char[line.length()];   // brackets opened but not closed yet
        int top = 0;
        boolean balanced = true;
        for (char c : line.toCharArray()) {
            if (c == '(' || c == '[' || c == '{') {
                stack[top++] = c;
            } else if (c == ')' || c == ']' || c == '}') {
                char want = c == ')' ? '(' : c == ']' ? '[' : '{';
                if (top == 0 || stack[top - 1] != want) {
                    balanced = false;   // nothing to close, or the wrong kind
                    break;
                }
                top--;
            }
        }
        System.out.println(balanced && top == 0 ? "YES" : "NO");   // anything left open is also wrong
    }
}

Time: O(L), where L is the length of the line · Extra space: O(L) for the stack

5Fewest boats across the river

GreedyTwo pointersSortingMedium

N people must cross a river. A boat carries at most two people, and the total weight in one boat can't be more than W kilograms. Nobody weighs more than W. What is the fewest number of boats needed to take everyone across?

Input
N and W (1 ≤ N ≤ 105, 1 ≤ W ≤ 109), then N weights, each from 1 to W.
Output
The fewest number of boats.

Example input

5 100
60 40 70 30 90

Output

3

90 goes alone (even with 30 the boat would carry 120), then 30 goes with 70, and 40 with 60.

Approach

Sort the weights and put one marker on the lightest person and one on the heaviest. The heaviest person needs a boat anyway. If the lightest person fits in with them, they share it; if not, nobody fits with the heaviest person, so they go alone. Either way, one boat leaves and the markers move inwards.

Why the lightest? If anyone can share with the heaviest person, the lightest can, and keeping the heavier people for later never needs fewer boats. Two weights can add up to 2 × 109, close to the limit of a 32-bit int, so the C++ and Java versions use 64-bit numbers to be safe.

Solution

Python
import sys

data = list(map(int, sys.stdin.read().split()))
n, limit = data[0], data[1]
weights = sorted(data[2:2 + n])

boats = 0
light, heavy = 0, n - 1      # the lightest and heaviest people still waiting
while light <= heavy:
    if light < heavy and weights[light] + weights[heavy] <= limit:
        light += 1           # the lightest person fits in with the heaviest
    heavy -= 1               # the heaviest person always leaves on this boat
    boats += 1
print(boats)
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    long long limit;
    cin >> n >> limit;
    vector<long long> w(n);   // two weights can add up to 2 x 10^9, right at the edge of int
    for (auto &x : w) cin >> x;
    sort(w.begin(), w.end());

    int boats = 0;
    int light = 0, heavy = n - 1;   // the lightest and heaviest people still waiting
    while (light <= heavy) {
        if (light < heavy && w[light] + w[heavy] <= limit)
            light++;                // the lightest person fits in with the heaviest
        heavy--;                    // the heaviest person always leaves on this boat
        boats++;
    }
    cout << boats << '\n';
}
Java
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long limit = sc.nextLong();
        long[] w = new long[n];   // two weights can add up to 2 x 10^9, right at the edge of int
        for (int i = 0; i < n; i++) w[i] = sc.nextLong();
        Arrays.sort(w);

        int boats = 0;
        int light = 0, heavy = n - 1;   // the lightest and heaviest people still waiting
        while (light <= heavy) {
            if (light < heavy && w[light] + w[heavy] <= limit)
                light++;                // the lightest person fits in with the heaviest
            heavy--;                    // the heaviest person always leaves on this boat
            boats++;
        }
        System.out.println(boats);
    }
}

Time: O(N log N) for the sort · Extra space: O(N)

6Buy once, sell once

ArraysGreedyEasy

You know what a share will cost on each of the next N days. You may buy one share on one day and sell it on a later day. What is the most profit you can make? If no trade makes a profit, you simply don't trade, so print 0.

Input
N (1 ≤ N ≤ 105), then N prices, each from 1 to 109.
Output
The largest profit, or 0.

Example 1 input

7
9 4 7 3 8 10 2

Output

7

Example 2 input

4
10 8 5 2

Output

0

Buy at 3 on day 4 and sell at 10 on day 6. In the second example the price only falls, so every trade loses money.

Approach

Trying every pair of days takes O(N²) steps. Instead, walk through the days once and remember cheapest, the lowest price on any day so far. Selling today makes today's price minus cheapest; keep the best of these, then update cheapest with today's price.

A common mistake is to subtract the lowest price of all from the highest. That fails when the highest price comes before the lowest: for 10 1 5 2 it gives 9, but you can't sell at 10 before you buy at 1, and the real answer is 4.

Solution

Python
import sys

data = list(map(int, sys.stdin.read().split()))
n, prices = data[0], data[1:]

cheapest = prices[0]    # the cheapest day to buy, so far
best = 0                # not trading at all makes 0
for p in prices[1:n]:
    best = max(best, p - cheapest)   # sell today, having bought on the cheapest earlier day
    cheapest = min(cheapest, p)
print(best)
C++
#include <algorithm>
#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    long long cheapest, best = 0;   // the cheapest day to buy so far; not trading makes 0
    cin >> cheapest;
    for (int i = 1; i < n; i++) {
        long long p;
        cin >> p;
        best = max(best, p - cheapest);   // sell today, having bought on the cheapest earlier day
        cheapest = min(cheapest, p);
    }
    cout << best << '\n';
}
Java
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long cheapest = sc.nextLong(), best = 0;   // the cheapest day to buy so far; not trading makes 0
        for (int i = 1; i < n; i++) {
            long p = sc.nextLong();
            best = Math.max(best, p - cheapest);   // sell today, having bought on the cheapest earlier day
            cheapest = Math.min(cheapest, p);
        }
        System.out.println(best);
    }
}

Time: O(N) · Extra space: O(1)

7Where does the line go out of order?

ArraysEasy

Students should stand in a line from the shortest to the tallest, and two students of the same height may stand next to each other. Given their heights in the order they are standing, print the position (counting from 1) of the first student who is shorter than the student just before them. If there is no such student, the line is in order, so print 0.

Input
N (1 ≤ N ≤ 105), then N heights, each from 1 to 109.
Output
The position of the first student out of order, or 0.

Example 1 input

6
150 152 152 149 160 158

Output

4

Example 2 input

3
140 140 141

Output

0

The 4th student (149) is shorter than the 3rd (152). Equal heights next to each other, like 152 152 and 140 140, are fine.

Approach

Compare each student with the one just before: start at the second student (index 1) and stop at the first one who is strictly shorter. Print that index plus 1, because positions count from 1 but arrays count from 0.

This short task hides three classic bugs worth checking for in your own code: starting the loop at index 0 (nobody stands before the first student), using ≤ instead of < (which wrongly flags equal heights), and printing the index without adding 1.

Solution

Python
import sys

data = list(map(int, sys.stdin.read().split()))
n, heights = data[0], data[1:]

answer = 0                             # 0 means the line is in order
for i in range(1, n):                  # compare each student with the one just before
    if heights[i] < heights[i - 1]:    # strictly shorter; equal heights are fine
        answer = i + 1                 # positions count from 1
        break
print(answer)
C++
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> h(n);
    for (int &x : h) cin >> x;

    int answer = 0;                  // 0 means the line is in order
    for (int i = 1; i < n; i++) {    // compare each student with the one just before
        if (h[i] < h[i - 1]) {       // strictly shorter; equal heights are fine
            answer = i + 1;          // positions count from 1
            break;
        }
    }
    cout << answer << '\n';
}
Java
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] h = new int[n];
        for (int i = 0; i < n; i++) h[i] = sc.nextInt();

        int answer = 0;                  // 0 means the line is in order
        for (int i = 1; i < n; i++) {    // compare each student with the one just before
            if (h[i] < h[i - 1]) {       // strictly shorter; equal heights are fine
                answer = i + 1;          // positions count from 1
                break;
            }
        }
        System.out.println(answer);
    }
}

Time: O(N) · Extra space: O(N) for the heights

8How many scored above the average?

ArraysMathsEasy

N students took a test. Print how many of them scored strictly more than the class average. The average is the total of all the scores divided by N, without rounding.

Input
N (1 ≤ N ≤ 105), then N scores, each from 0 to 109.
Output
The number of students who scored more than the average.

Example 1 input

5
3 4 4 5 9

Output

1

Example 2 input

4
1 2 2 2

Output

3

In the first example the average is 25 ÷ 5 = 5, and only 9 is above it. In the second it is 7 ÷ 4 = 1.75, so all three 2s are above it.

Approach

Add up the scores, then count the scores above the average. Two things go wrong easily here. The total can reach 105 × 109 = 1014, which overflows an int, so use long long in C++ or long in Java. And rounding the average breaks the answer: in the second example, rounding 1.75 up to 2 would give 0 instead of 3.

The safest test needs no division at all: a score x is above the average exactly when x × N > total. Both sides are whole numbers (at most 1014), so there are no fractions to worry about.

Solution

Python
import sys

data = list(map(int, sys.stdin.read().split()))
n, scores = data[0], data[1:1 + data[0]]

total = sum(scores)
# x > total / n is the same as x * n > total, and that needs no fractions
print(sum(1 for x in scores if x * n > total))
C++
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<long long> s(n);
    long long total = 0;   // up to 10^14, far too big for int
    for (auto &x : s) {
        cin >> x;
        total += x;
    }

    // x > total / n is the same as x * n > total, and that needs no fractions
    int count = 0;
    for (long long x : s)
        if (x * n > total) count++;
    cout << count << '\n';
}
Java
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long[] s = new long[n];
        long total = 0;   // up to 10^14, far too big for int
        for (int i = 0; i < n; i++) {
            s[i] = sc.nextLong();
            total += s[i];
        }

        // x > total / n is the same as x * n > total, and that needs no fractions
        int count = 0;
        for (long x : s)
            if (x * n > total) count++;
        System.out.println(count);
    }
}

Time: O(N) · Extra space: O(N) for the scores

Questions

What does Cognizant's GenC selection include?

Cognizant's campus pages say every role needs a communication assessment, an aptitude assessment and a technical assessment, followed by a technical interview with a subject expert.

Who can apply for Cognizant GenC 2027?

Its 2027 on-campus page lists B.E., B.Tech, M.E. and M.Tech students, except Leather, Food and Fashion Technology and dual-degree students. Three-year graduates have a separate Analyst Trainee track.

How many coding questions are in Cognizant's test?

Cognizant doesn't publish it, so we haven't guessed. Practise finishing an easy problem in 15 to 20 minutes.

Are these real Cognizant questions?

No. We wrote them ourselves in the style of the question types students commonly report: strings, counting, stacks, greedy choices and fixing broken logic.

Were these solutions tested?

Yes. We ran every solution in Python, C++ and Java on the examples, on extra edge cases, on random inputs checked against a slow but simple answer, and on the largest inputs the limits allow.

More placement prep