Java Coding Interview Questions: Programs Asked in Service-Company Drives

Prepare the short Java programs that recur in fresher drives. Learn the core string, array, number and collections patterns, then trace an O(n) Two-Sum solution.

KnowledgeGate Team

Exam prep & CS education

Updated 1 Aug 20265 min read

Service-company drives such as TCS, Infosys, Wipro and Cognizant tend to reuse a fairly predictable set of short Java programs. The difficult part is not remembering every line. It is recognising when a clean O(n) solution can replace a nested O(n^2) scan while the interviewer is quietly checking your reasoning.

The programs fall into three groups: eight string routines, twelve array and number routines, and six collections and OOP judgement calls. One idea, a HashMap from value to index, carries the biggest jump in most of them, and Two-Sum is the cleanest place to watch it turn a nested scan into a single pass.

What service-company coding rounds test

Most fresher rounds test correctness on standard patterns, readable Java and basic complexity awareness. They are usually not looking for an exotic graph algorithm. They want a working program and a one-line explanation of why the approach is efficient.

That makes preparation manageable. Learn the patterns, write them without copying, test edge cases, and state time and auxiliary space after every answer. The Placement Preparation category helps you place this coding work beside aptitude and interview preparation.

String programs: the core eight

These eight are the string operations a fresher is asked to write and explain most often:

  1. Reverse a string: traverse from the last character to the first, or use StringBuilder.reverse() when library use is allowed.

  2. Check a palindrome: compare characters from both ends with two pointers until they meet.

  3. Count vowels and consonants: normalise case, scan once, and classify only alphabetic characters.

  4. Find the first non-repeating character: build a frequency map, then scan the original string again to preserve order.

  5. Check two strings for anagrams: compare frequency counts after applying the same case and whitespace rules.

  6. Count character frequency: update Map<Character, Integer> with each character in one pass.

  7. Remove duplicate characters: add characters to a LinkedHashSet, or track them in a set while building the answer.

  8. Check string rotation: for equal-length strings, test whether the second occurs inside first + first.

Before coding, ask whether case, spaces and punctuation matter. That small clarification prevents a correct algorithm from solving the wrong version of the question.

Array and number programs: the core twelve

The next group repeats across written tests and live coding screens:

  • Maximum and minimum: keep two running values during one traversal.

  • Second largest: maintain the largest and second-largest distinct values without sorting.

  • Missing number: for values from 1 to n, compute n * (n + 1) / 2 and subtract the observed sum.

  • Duplicate detection: use a HashSet; the first value that cannot be added is a duplicate.

  • Reverse an array: swap the left and right elements while moving two pointers inward.

  • Rotate an array: use reversal in three steps for O(n) time and O(1) extra space.

  • Maximum subarray: Kadane's algorithm keeps the best sum ending here and the best seen overall.

  • Move zeros to the end: compact non-zero values forward, then fill the remaining positions with zero.

  • Two-Sum: store each seen value and its index in a HashMap while looking for its complement.

  • Merge sorted arrays: advance one pointer in each array and append the smaller current value.

  • Frequency count: update a HashMap in one pass, then read counts without rescanning the array.

  • Fibonacci, prime and GCD: use an iterative Fibonacci loop, trial division up to the square root for primality, and Euclid's algorithm for GCD.

For clean versions of that last group, use Classic Programs in C, Java and Python. Do not just read the programs. Run each with a normal case, an empty or minimal case, and a case containing repeated values.

Worked example: Two-Sum from O(n^2) to O(n)

Problem: given the array [2, 7, 11, 15] and target 9, return the indices of two values whose sum is 9.

The naive method checks every pair. The first pair is (2, 7), and 2 + 7 = 9, so the answer is indices (0, 1). Two nested loops can examine a number of pairs proportional to n squared, giving O(n^2) time and O(1) auxiliary space.

The optimal method uses one pass and a HashMap from value to index:

  1. At i = 0, val = 2. Compute need = 9 - 2 = 7. The map does not contain 7, so store {2: 0}.

  2. At i = 1, val = 7. Compute need = 9 - 7 = 2. The map contains 2 at index 0, so return (0, 1).

The result is indices (0, 1). Each element needs one expected constant-time lookup, so the solution takes O(n) time and O(n) space.

static int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> seen = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int need = target - nums[i];
        if (seen.containsKey(need)) {
            return new int[] {seen.get(need), i};
        }
        seen.put(nums[i], i);
    }
    return new int[] {-1, -1};
}
Two panel trace of Two-Sum on the array 2, 7, 11, 15 with target 9. At index 0 the value 2 needs 7, which is absent, so 2 is stored against index 0. At index 1 the value 7 needs 2, finds it at index 0, and the answer is (0, 1).

The ordering matters. Check for the complement before inserting the current value, especially when the target can be twice one value. Otherwise one array element may incorrectly match itself.

Collections and OOP in Java: the core six questions

Short exercises often test whether you can choose a Java feature, not merely write a loop.

  • Use a HashMap for counts and a HashSet for fast membership or de-duplication.

  • Explain that an array has fixed length, while an ArrayList grows and provides collection methods.

  • Sort objects with a Comparator, such as sorting employees by score and then by name.

  • Reverse mutable text with StringBuilder instead of repeated string concatenation.

  • Use .equals() for string content; == compares whether references point to the same object.

  • Explain autoboxing, and do not rely on Integer reference equality because cached instances can make == appear inconsistent.

KnowledgeGate's programming-languages practice set runs past 1,200 questions, and the Java ones lean hard on exactly these choices: which structure to reach for, and what == actually compares.

Complexity awareness that wins the round

Finish every program with two sentences: one for time and one for auxiliary space. For a frequency map, say O(n) expected time and O(n) space. For two nested loops over the same input, say O(n^2) time. For an in-place two-pointer reversal, say O(n) time and O(1) extra space.

When asked, "Can you do better than O(n^2)?", name the bottleneck first. Then name the structure that removes it. A HashMap replaces repeated searching with expected constant-time lookup; sorting may permit a linear two-pointer scan after O(n log n) preprocessing. The DSA interview questions for placements guide develops these reusable patterns further.

Short version and next step

Know the string, array, number and collections patterns, but do not present them as memorised recipes. Explain the invariant, test an edge case, and volunteer the complexity. That is what turns a merely working answer into a convincing interview answer.

Write every program yourself in the Java Programming course, then rehearse a mixed set under time with the Mera Placement Hoga Anushasan bundle. Start with Two-Sum and the eight string problems, because together they force you to practise maps, sets, two pointers and precise edge-case handling.