Autocoder

IBM coding round questions

Last updated 2026-11-19

Third-party guides to IBM's fresher assessment describe a short coding section with two questions in roughly an hour, on top of aptitude and technical multiple-choice sections. That shape favours people who can read a problem once, pick a plain approach and finish with a few minutes left to test. The twelve exercises below are in that register: string handling, array shuffling, small number theory, a loop to trace by hand, and two SQL joins.

They are original practice problems, not a copy of any past paper. Pair them with IBM interview questions for the technical interview and with the DSA coding round guide for a pacing plan.

Reported formatTwo coding questions, about 55 minutes
Difficulty hereEasy to medium
LanguagesPython and Java shown

Working through the set

Treat the list as a timed drill. Pick two problems at random, give yourself fifty-five minutes, and write both solutions in the language you would use on test day. Afterwards compare your code with the solution shown and read the common-mistakes note, which usually names the exact case that fails hidden tests.

Two habits pay off at this level. First, read the input format twice: many lost marks come from a wrong assumption about whether numbers arrive on one line or several. Second, run your code by hand on the smallest input, usually an empty list or a single character, before running it on the sample.

Where the SQL fits

Some technology tracks include a database portion in the technical section. The two queries here use a self join and an anti join, which are the two join shapes that trip up beginners most often. Sample tables are described in each answer so you can recreate them locally.

Hiring status

No sourced IBM statement on fresher drives or intake numbers is held on this site, so none are given here. Apply through IBM's careers site at ibm.com/careers and read the format in your own invitation email, since it can change between drives.

IBM coding round questions: questions with worked answers

  1. 1

    Reverse the order of the words in a sentence.

    easy

    Split on whitespace, reverse the list of words and join with single spaces. Splitting on runs of whitespace also removes leading, trailing and repeated spaces. O(n) time and space. Common mistakes: reversing the characters of the whole string, which also reverses each word, and splitting on a single space, which leaves empty tokens behind.

    python
    def reverse_words(sentence):
        return ' '.join(reversed(sentence.split()))
    java
    class Words {
        static String reverseWords(String s) {
            String[] parts = s.trim().split("\\s+");
            StringBuilder sb = new StringBuilder();
            for (int i = parts.length - 1; i >= 0; i--) {
                sb.append(parts[i]);
                if (i > 0) sb.append(' ');
            }
            return sb.toString();
        }
    }
  2. 2

    One number is missing from a list that should contain 1 to n. Find it.

    easy

    The sum of 1..n is n(n+1)/2. Subtract the sum of the given list and what remains is the missing number. O(n) time, O(1) space. Common mistakes: taking n as the length of the given list, when n is one more because a number is missing, and using an int for the sum when n is large.

    python
    def missing_number(nums):
        n = len(nums) + 1
        return n * (n + 1) // 2 - sum(nums)
    java
    class Missing {
        static long missing(int[] nums) {
            long n = nums.length + 1;
            long expected = n * (n + 1) / 2;
            for (int x : nums) expected -= x;
            return expected;
        }
    }
  3. 3

    Find the second largest distinct value in an array.

    easy

    Track the largest and the second largest in one pass. A value equal to the current largest must be ignored, otherwise duplicates fill both slots. If fewer than two distinct values exist there is no answer. O(n) time, O(1) space. Common mistakes: sorting and taking index -2, which returns a duplicate of the maximum, and starting both trackers at zero so negatives are lost.

    python
    def second_largest(nums):
        first = second = None
        for x in nums:
            if first is None or x > first:
                first, second = x, first
            elif x != first and (second is None or x > second):
                second = x
        return second
    java
    class Second {
        static Integer secondLargest(int[] nums) {
            Integer first = null, second = null;
            for (int x : nums) {
                if (first == null || x > first) { second = first; first = x; }
                else if (x != first && (second == null || x > second)) second = x;
            }
            return second;
        }
    }
  4. 4

    Rotate an array to the right by k positions.

    easy

    Reduce k modulo the length, then slice: the last k items go to the front. In Java, do it in place with three reversals: the whole array, the first k items, then the rest. O(n) time, O(1) extra space for the reversal method. Common mistakes: not taking k modulo n, so large k breaks, and dividing by zero on an empty array.

    python
    def rotate_right(arr, k):
        if not arr:
            return arr
        k %= len(arr)
        return arr[len(arr) - k:] + arr[:len(arr) - k]
    java
    class Rotate {
        static void rotateRight(int[] a, int k) {
            if (a.length == 0) return;
            k %= a.length;
            reverse(a, 0, a.length - 1);
            reverse(a, 0, k - 1);
            reverse(a, k, a.length - 1);
        }
        private static void reverse(int[] a, int i, int j) {
            while (i < j) { int t = a[i]; a[i++] = a[j]; a[j--] = t; }
        }
    }
  5. 5

    Check whether a phrase is a palindrome when only letters and digits count and case is ignored.

    easy

    Use two pointers moving inward. Skip anything that is not alphanumeric, then compare the lowercase characters. O(n) time, O(1) space. Common mistakes: building a cleaned copy when the problem asks for constant space, and forgetting to bound the inner skip loops so the pointers cross.

    python
    def is_palindrome(text):
        i, j = 0, len(text) - 1
        while i < j:
            while i < j and not text[i].isalnum():
                i += 1
            while i < j and not text[j].isalnum():
                j -= 1
            if text[i].lower() != text[j].lower():
                return False
            i += 1
            j -= 1
        return True
    java
    class Pal {
        static boolean isPalindrome(String s) {
            int i = 0, j = s.length() - 1;
            while (i < j) {
                while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;
                while (i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;
                if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) return false;
                i++; j--;
            }
            return true;
        }
    }
  6. 6

    Count the vowels, consonants and digits in a string.

    easy

    Scan once and classify each character: letters in aeiou are vowels, other letters are consonants, digits are digits, and everything else is ignored. O(n) time, O(1) space. Common mistakes: forgetting uppercase vowels, and counting spaces or punctuation as consonants.

    python
    def classify(text):
        vowels = consonants = digits = 0
        for ch in text.lower():
            if ch in 'aeiou':
                vowels += 1
            elif ch.isalpha():
                consonants += 1
            elif ch.isdigit():
                digits += 1
        return vowels, consonants, digits
    java
    class Classify {
        static int[] count(String s) {
            int[] r = new int[3];
            for (char ch : s.toLowerCase().toCharArray()) {
                if ("aeiou".indexOf(ch) >= 0) r[0]++;
                else if (Character.isLetter(ch)) r[1]++;
                else if (Character.isDigit(ch)) r[2]++;
            }
            return r;
        }
    }
  7. 7

    List all primes up to n.

    medium

    Sieve of Eratosthenes. Mark everything as prime, then for each prime p starting from 2 mark its multiples from p*p as composite. Stop at the square root of n. O(n log log n) time, O(n) space. Common mistakes: testing each number by trial division up to n, and starting the inner loop at 2p, which is correct but needless work.

    python
    def primes_upto(n):
        if n < 2:
            return []
        flags = [True] * (n + 1)
        flags[0] = flags[1] = False
        p = 2
        while p * p <= n:
            if flags[p]:
                for m in range(p * p, n + 1, p):
                    flags[m] = False
            p += 1
        return [i for i, ok in enumerate(flags) if ok]
    java
    import java.util.*;
    
    class Sieve {
        static List<Integer> primesUpTo(int n) {
            List<Integer> out = new ArrayList<>();
            if (n < 2) return out;
            boolean[] composite = new boolean[n + 1];
            for (int p = 2; (long) p * p <= n; p++)
                if (!composite[p])
                    for (int m = p * p; m <= n; m += p) composite[m] = true;
            for (int i = 2; i <= n; i++) if (!composite[i]) out.add(i);
            return out;
        }
    }
  8. 8

    Convert a binary string to its decimal value without using a built-in converter.

    easy

    Scan left to right keeping a running value. For each bit, double the value and add the bit. This is Horner's rule. O(n) time, O(1) space. Common mistakes: treating the leftmost bit as the least significant, and not rejecting characters other than 0 and 1.

    python
    def binary_to_decimal(bits):
        value = 0
        for ch in bits:
            if ch not in '01':
                raise ValueError('not a binary string')
            value = value * 2 + (ch == '1')
        return value
    java
    class Binary {
        static long toDecimal(String bits) {
            long value = 0;
            for (char ch : bits.toCharArray()) {
                if (ch != '0' && ch != '1') throw new IllegalArgumentException("not binary");
                value = value * 2 + (ch - '0');
            }
            return value;
        }
    }
  9. 9

    Trace the loop by hand: what values are recorded?

    medium

    Start with i = 1 and total = 0. While i is at most 10: an even i adds i to total, an odd i subtracts 1, then i grows by 3, and total is recorded. The iterations are i = 1, 4, 7, 10, giving -1, 3, 2, 12. Writing a table of i, total and the branch taken is the reliable way to answer such questions. Common mistakes: updating i before the test of its parity, and recording the value before the update.

    python
    def trace():
        log, i, total = [], 1, 0
        while i <= 10:
            if i % 2 == 0:
                total += i
            else:
                total -= 1
            i += 3
            log.append(total)
        return log
    java
    import java.util.*;
    
    class Trace {
        static List<Integer> trace() {
            List<Integer> log = new ArrayList<>();
            int i = 1, total = 0;
            while (i <= 10) {
                if (i % 2 == 0) total += i;
                else total -= 1;
                i += 3;
                log.add(total);
            }
            return log;
        }
    }
  10. 10

    SQL: list employees who earn more than their own manager. Table employees(id, name, salary, manager_id, dept_id).

    medium

    Join the table to itself: one alias is the employee and the other is the manager, matched on manager_id = id. Keep the rows where the employee's salary is larger. An inner join drops employees with no manager, which is what the question wants. Common mistakes: comparing against the average salary instead, and using a left join, which keeps top-level managers with NULL comparisons.

    sql
    SELECT e.name
    FROM employees e
    JOIN employees m ON e.manager_id = m.id
    WHERE e.salary > m.salary
    ORDER BY e.name;
  11. 11

    SQL: list departments that have no employees. Tables departments(id, name) and employees(id, name, dept_id).

    medium

    Left join departments to employees on the department id, then keep only the rows where the employee side is NULL. Those are departments that found no match. An alternative is NOT EXISTS, which many engines optimise equally well. Common mistakes: an inner join, which can never show an unmatched row, and testing the NULL on a department column instead of an employee column.

    sql
    SELECT d.name
    FROM departments d
    LEFT JOIN employees e ON e.dept_id = d.id
    WHERE e.id IS NULL
    ORDER BY d.name;
  12. 12

    Count the distinct pairs of values in an array whose difference is exactly k (k > 0).

    medium

    Put the values in a set. For every distinct value x, check whether x + k is also present; each success is one pair. O(n) time, O(n) space. Common mistakes: checking x - k as well, which counts every pair twice, and using nested loops, which is O(n squared). The case k = 0 needs counts instead of a set and is usually a separate rule.

    python
    def pairs_with_difference(nums, k):
        seen = set(nums)
        return sum(1 for x in seen if x + k in seen)
    java
    import java.util.*;
    
    class Diff {
        static int pairs(int[] nums, int k) {
            Set<Integer> seen = new HashSet<>();
            for (int x : nums) seen.add(x);
            int count = 0;
            for (int x : seen) if (seen.contains(x + k)) count++;
            return count;
        }
    }

Frequently asked questions

How many coding questions are in the IBM test?

A third-party guide reports two coding questions in about 55 minutes, but formats change between drives. Confirm the details in your own invitation email.

Can I use any language?

Reports suggest several mainstream languages are accepted, but check the test instructions. This page shows Python and Java, with SQL for the two query problems.

Which topics should I revise first for an easy-to-medium test?

Strings, arrays, basic number logic, simple loops and nested conditions. Add a self join and a left join in SQL if your track mentions databases.

What should I do if my code passes the sample but fails hidden tests?

Look at empty inputs, a single element, duplicates, negative numbers and very large values. Most hidden-test failures at this level come from those cases.

Where do I find real IBM openings?

On ibm.com/careers. Treat any third-party description of the process, including the one cited here, as a guide and not as an announcement.

Sources

Related guides

More in Company Interview Questions

See all in this section