Skills101
← All posts

Coding Questions for Placement Tests — 6 Classics Solved in C++, Java and Python

Pankaj Sharma ·

Coding rounds in TCS NQT, Wipro, Accenture, Deloitte and similar tests rarely ask anything exotic. They ask short problems on arrays, strings and simple maths — and students lose marks on input handling, edge cases and duplicates, not on the idea.

Below are six classics, each solved in C++, Java and Python, reading input the way an online judge sends it. The Input: comment at the top of each program shows the sample input, and the block after it shows the output.

How we checked: every program on this page is compiled and run by our build with the sample input, and its real output must match the output shown. If you copy a solution, it works.

Before you start: pick the language you will use in the test and solve all six in it first. Switching languages mid-preparation costs more than any language advantage.

1. Valid palindrome (ignore case and punctuation)

Problem: read a line and print Yes if it reads the same forwards and backwards when you keep only letters and digits and ignore case, else No.

Idea: clean the string (letters/digits only, lower case), then compare it with its reverse. O(n) time.

Edge cases: an empty or all-punctuation line counts as a palindrome; mixed case (Aa).

# Input: A man, a plan, a canal: Panama
s = input()
t = [c.lower() for c in s if c.isalnum()]
print("Yes" if t == t[::-1] else "No")
Yes
// Input: A man, a plan, a canal: Panama
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        StringBuilder b = new StringBuilder();
        for (char c : s.toCharArray())
            if (Character.isLetterOrDigit(c)) b.append(Character.toLowerCase(c));
        String t = b.toString();
        System.out.println(t.equals(b.reverse().toString()) ? "Yes" : "No");
    }
}
Yes
// Input: A man, a plan, a canal: Panama
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
    string s, t;
    getline(cin, s);
    for (char c : s)
        if (isalnum((unsigned char)c)) t += (char)tolower((unsigned char)c);
    string r(t.rbegin(), t.rend());
    cout << (t == r ? "Yes" : "No") << "\n";
}
Yes

2. Second largest element (distinct)

Problem: read n and n integers; print the second largest distinct value, or -1 if there isn't one.

Idea: one pass, keeping the largest and second largest. Skip values equal to the largest — that is the duplicate trap (in 10 5 10 8, the answer is 8, not 10). O(n) time, O(1) space; no sorting needed.

# Input: 6
# Input: 10 5 10 8 3 8
n = int(input())
a = list(map(int, input().split()))
first = second = None
for x in a:
    if first is None or x > first:
        first, second = x, first
    elif x != first and (second is None or x > second):
        second = x
print(second if second is not None else -1)
8
// Input: 6
// Input: 10 5 10 8 3 8
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long first = Long.MIN_VALUE, second = Long.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            long x = sc.nextLong();
            if (x > first) { second = first; first = x; }
            else if (x < first && x > second) second = x;
        }
        System.out.println(second == Long.MIN_VALUE ? -1 : second);
    }
}
8
// Input: 6
// Input: 10 5 10 8 3 8
#include <iostream>
#include <climits>
using namespace std;

int main() {
    int n;
    cin >> n;
    long long first = LLONG_MIN, second = LLONG_MIN;
    for (int i = 0; i < n; i++) {
        long long x;
        cin >> x;
        if (x > first) { second = first; first = x; }
        else if (x < first && x > second) second = x;
    }
    cout << (second == LLONG_MIN ? -1 : second) << "\n";
}
8

3. Missing number from 1 to n

Problem: the numbers 1 to n are given with exactly one missing (n − 1 numbers). Print the missing one.

Idea: the sum of 1 to n is n(n + 1)/2; subtract the sum you read. Use a 64-bit type — for n = 100,000 the total is 5,000,050,000, which overflows a 32-bit int.

# Input: 6
# Input: 1 2 4 5 6
n = int(input())
a = list(map(int, input().split()))
print(n * (n + 1) // 2 - sum(a))
3
// Input: 6
// Input: 1 2 4 5 6
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long total = (long) n * (n + 1) / 2;
        for (int i = 0; i < n - 1; i++) total -= sc.nextLong();
        System.out.println(total);
    }
}
3
// Input: 6
// Input: 1 2 4 5 6
#include <iostream>
using namespace std;

int main() {
    long long n;
    cin >> n;
    long long total = n * (n + 1) / 2;
    for (int i = 0; i < n - 1; i++) {
        long long x;
        cin >> x;
        total -= x;
    }
    cout << total << "\n";
}
3

4. Move zeroes to the end (keep order)

Problem: read n integers and move every 0 to the end while keeping the order of the other numbers. Print the result on one line.

Idea: a write pointer k: copy each non-zero value to position k, then fill the rest with zeros. O(n) time, in place.

# Input: 7
# Input: 0 1 0 3 12 0 5
n = int(input())
a = list(map(int, input().split()))
nz = [x for x in a if x != 0]
print(*(nz + [0] * (n - len(nz))))
1 3 12 5 0 0 0
// Input: 7
// Input: 0 1 0 3 12 0 5
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = sc.nextInt();
        int k = 0;
        for (int i = 0; i < n; i++) if (a[i] != 0) a[k++] = a[i];
        while (k < n) a[k++] = 0;
        StringBuilder out = new StringBuilder();
        for (int i = 0; i < n; i++) out.append(i > 0 ? " " : "").append(a[i]);
        System.out.println(out);
    }
}
1 3 12 5 0 0 0
// Input: 7
// Input: 0 1 0 3 12 0 5
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (int &x : a) cin >> x;
    int k = 0;
    for (int i = 0; i < n; i++) if (a[i] != 0) a[k++] = a[i];
    while (k < n) a[k++] = 0;
    for (int i = 0; i < n; i++) cout << (i ? " " : "") << a[i];
    cout << "\n";
}
1 3 12 5 0 0 0

5. Character frequency (in order of first appearance)

Problem: read a word and print each character with its count, in the order the characters first appear, as char:count separated by spaces.

Idea: count with a map that remembers insertion order (Python dict, Java LinkedHashMap), or keep a separate list of first appearances (C++). O(n) time.

# Input: programming
s = input().strip()
counts = {}
for c in s:
    counts[c] = counts.get(c, 0) + 1
print(" ".join(f"{c}:{k}" for c, k in counts.items()))
p:1 r:2 o:1 g:2 a:1 m:2 i:1 n:1
// Input: programming
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String s = new Scanner(System.in).next();
        Map<Character, Integer> counts = new LinkedHashMap<>();
        for (char c : s.toCharArray()) counts.merge(c, 1, Integer::sum);
        StringBuilder out = new StringBuilder();
        for (Map.Entry<Character, Integer> e : counts.entrySet())
            out.append(out.length() > 0 ? " " : "").append(e.getKey()).append(':').append(e.getValue());
        System.out.println(out);
    }
}
p:1 r:2 o:1 g:2 a:1 m:2 i:1 n:1
// Input: programming
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    string s;
    cin >> s;
    int count[256] = {0};
    vector<char> order;
    for (char c : s) {
        if (count[(unsigned char)c]++ == 0) order.push_back(c);
    }
    for (size_t i = 0; i < order.size(); i++)
        cout << (i ? " " : "") << order[i] << ':' << count[(unsigned char)order[i]];
    cout << "\n";
}
p:1 r:2 o:1 g:2 a:1 m:2 i:1 n:1

6. Count primes up to n (Sieve of Eratosthenes)

Problem: read n and print how many primes are ≤ n.

Idea: checking each number separately is slow for large n. The sieve marks multiples of each prime starting from p², in O(n log log n) time.

# Input: 50
n = int(input())
is_prime = [True] * (n + 1)
is_prime[0:2] = [False, False]
p = 2
while p * p <= n:
    if is_prime[p]:
        for m in range(p * p, n + 1, p):
            is_prime[m] = False
    p += 1
print(sum(is_prime))
15
// Input: 50
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int n = new Scanner(System.in).nextInt();
        boolean[] composite = new boolean[n + 1];
        int count = 0;
        for (int p = 2; p <= n; p++) {
            if (composite[p]) continue;
            count++;
            for (long m = (long) p * p; m <= n; m += p) composite[(int) m] = true;
        }
        System.out.println(count);
    }
}
15
// Input: 50
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<bool> composite(n + 1, false);
    int count = 0;
    for (int p = 2; p <= n; p++) {
        if (composite[p]) continue;
        count++;
        for (long long m = (long long)p * p; m <= n; m += p) composite[m] = true;
    }
    cout << count << "\n";
}
15

Five habits that save marks in coding rounds

  1. Read input exactly as described — line by line or token by token. Many "wrong answers" are input-reading bugs.
  2. Print exactly the format asked — no extra text like "Answer:", no trailing commas.
  3. Use 64-bit integers for sums and products (long in Java, long long in C++).
  4. Test the edge cases yourself: one element, all equal, zeros, negative numbers, the largest n.
  5. Submit a working solution first, then optimise. Most tests give partial marks for passing some test cases.

Practise more

Frequently asked questions

What coding questions are asked in placement tests?

Service-company tests usually ask easy-to-medium problems on arrays, strings and basic maths — palindromes, second largest, missing number, frequency counting, primes, rotation and sorting-based problems. Product companies ask harder DSA problems.

Which language is best for placement coding rounds?

The one you know best. C++, Java and Python are accepted almost everywhere. C++ and Java are faster at run time, and Python is quicker to write; for easy-to-medium problems, any of them is fine.

Why does my code pass samples but fail hidden test cases?

Usually an edge case (empty input, duplicates, one element), integer overflow, or reading input in the wrong format. Test those yourself before submitting.

How many coding problems are there in TCS NQT and Wipro?

TCS NQT's Advanced section and Wipro's NLTH both commonly report 2 coding problems, in about 90 and 60 minutes respectively. Check your test invitation for the exact pattern.

🎯 Today’s placement challenge — 10 questions, no login. Can you score 10/10?Take today’s challenge →