Placement Prep
Accenture Internship OA

Java OA Coding

Eight original Java exercises with explanations, edge cases, and a small 1D dynamic-programming backup.

Research checked: 13 November 2026. This is an original practice curriculum for the 16 November internship OA, not a list of promised questions. Recent internship reports describe Java as an available language and easy–medium coding; confirm the version and permitted languages in your own mock.

Java survival notes

Use int[] for fixed-size numeric data, StringBuilder for repeated string construction, HashMap for counts, and HashSet for membership. Arrays use .length, strings use .length(), and collections use .size(). Compare string contents with .equals(), not ==.

An int can overflow around 2.1 billion. Accumulate large totals in long; cast before multiplication: (long) a * b. Integer division truncates toward zero. Java % can be negative for negative operands. Sort with Arrays.sort(a); this changes the original array, so copy it if the contract requires preservation.

Input contract: the snippets below are methods. Put them inside class Solution; add import java.util.*; when a snippet uses collections or arrays. For a local test, add a main with System.out.println(method(...)). In the OA, keep the supplied class/method signature. If standard input is required, use the exact specified token/line layout; do not print prompts or extra labels.

import java.util.*;

class Solution {
    static long sum(int[] a) {
        long total = 0;
        for (int x : a) total += x;
        return total;
    }
    public static void main(String[] args) {
        System.out.println(sum(new int[]{2, 3, 4})); // 9
    }
}

For each exercise: clarify inputs, try for 15–20 minutes, test the examples and an edge case, then open the solution. The independent exercises and two mixed mocks are separate sets.

J1 — Sum the qualifying readings

Return the sum of array elements divisible by both 3 and 5. Empty input returns zero; negative values are allowed. At most 100,000 values, each within the Java int range. [15, 9, 30, -15, 0] → 30.

Hint and worked solution

Divisibility by both 3 and 5 is divisibility by 15. Zero qualifies but contributes zero. Each element is considered independently.

static long qualifyingSum(int[] a) {
    long total = 0;
    for (int x : a) {
        if (x % 15 == 0) total += x;
    }
    return total;
}

O(n) time, O(1) extra space. Test [] → 0, [3, 5] → 0 (using OR would be wrong), and [1500000000, 1500000000] → 3000000000.

  • Solve J1 and explain why the accumulator is long.

J2 — Keep even-length vowel words

Given a non-null sentence of ASCII letters separated by whitespace, return the words whose length is even and whose first letter is a vowel, ignoring case. Preserve order and original spelling; join matches with one space. Empty or whitespace-only input returns "". "An owl eats APPLE under ice" → "An eats".

Hint and worked solution

Trim before splitting so an empty sentence has no words. Test the first character against a small vowel set.

static String vowelWords(String sentence) {
    String s = sentence.trim();
    if (s.isEmpty()) return "";
    StringBuilder result = new StringBuilder();
    for (String word : s.split("\\s+")) {
        char first = Character.toLowerCase(word.charAt(0));
        if (word.length() % 2 == 0 && "aeiou".indexOf(first) >= 0) {
            if (result.length() > 0) result.append(' ');
            result.append(word);
        }
    }
    return result.toString();
}

O(n) time and O(n) space for splitting and output, where n is sentence length. Test " ECHO\tup " → "ECHO up", "sky" → "", and whitespace only. Punctuation is outside this exercise's contract; do not silently invent token rules in a real question.

  • Solve J2 with mixed case and repeated whitespace.

J3 — First unique lowercase character

Return the index of the first character occurring once in a lowercase-English string, or -1 if none exists. "swiss" → 1; "aabb" → -1.

Hint and worked solution

Count first, then scan the original string. A 26-element array is enough because the alphabet is explicitly constrained.

static int firstUnique(String s) {
    int[] count = new int[26];
    for (int i = 0; i < s.length(); i++) count[s.charAt(i) - 'a']++;
    for (int i = 0; i < s.length(); i++) {
        if (count[s.charAt(i) - 'a'] == 1) return i;
    }
    return -1;
}

O(n) time, O(1) extra space for the fixed alphabet. "" → -1, "z" → 0, "aab" → 2. Use a map instead if the input domain is not a fixed lowercase alphabet.

  • Solve J3 without losing the original character order.

J4 — Second distinct smallest value

Return the second distinct smallest integer in an array, or null if fewer than two distinct values exist. Do not mutate the input. [4, 1, 1, 3] → 3.

Hint and worked solution

Sort a copy, then skip copies of the minimum. A boxed Integer permits a clear missing-result value without confusing it with a valid integer.

static Integer secondSmallest(int[] a) {
    if (a.length < 2) return null;
    int[] sorted = Arrays.copyOf(a, a.length);
    Arrays.sort(sorted);
    for (int i = 1; i < sorted.length; i++) {
        if (sorted[i] != sorted[0]) return sorted[i];
    }
    return null;
}

O(n log n) time and O(n) extra space for the copy. Test [] → null, [2, 2] → null, and [-5, -2, -5] → -2. An optional improvement keeps two distinct minima in one pass; the sorted-copy solution is sufficient for learning this pattern.

  • Solve J4 and distinguish second smallest from second distinct smallest.

J5 — Count divisible digit windows

Given a non-null decimal digit string, count its contiguous windows of exactly three digits whose numeric value is divisible by 3. Leading zeros are permitted. "11021" → 2: the windows are 110, 102, and 021; both 102 and 021 qualify.

Hint and worked solution

A number is divisible by 3 when its digit sum is divisible by 3. Keep a rolling sum of the last three digits; no parsing or large integers are necessary.

static int divisibleTriples(String digits) {
    int sum = 0, answer = 0;
    for (int i = 0; i < digits.length(); i++) {
        sum += digits.charAt(i) - '0';
        if (i >= 3) sum -= digits.charAt(i - 3) - '0';
        if (i >= 2 && sum % 3 == 0) answer++;
    }
    return answer;
}

O(n) time, O(1) extra space. "12" → 0, "0000" → 2, "1234" → 2. Check the supplied examples independently; do not carry a mistaken expected value into your code.

  • Solve J5 and handle overlapping windows and leading zeros.

J6 — Longest segment within a budget

Given non-negative item costs and a non-negative long budget, return the maximum length of a contiguous segment whose sum is at most the budget. At most 100,000 costs. [2, 1, 3, 1, 1], budget 5 → 3.

Hint and worked solution

Expand the right end, then shrink the left while the budget is exceeded. Non-negative costs make shrinking safe: removing a value never increases the sum. This method is not valid for arbitrary negative costs.

static int longestAffordable(int[] costs, long budget) {
    int left = 0, best = 0;
    long sum = 0;
    for (int right = 0; right < costs.length; right++) {
        sum += costs[right];
        while (sum > budget && left <= right) sum -= costs[left++];
        best = Math.max(best, right - left + 1);
    }
    return best;
}

O(n) time: each boundary moves forward at most n times. O(1) extra space. Test [] → 0, [5] with budget 2 → 0, and [0, 0, 1] with budget 0 → 2.

  • Solve J6 and explain why non-negative costs matter.

J7 — Pairs of matching labels

Count unordered pairs of equal integers at different indices. Return long. [2, 2, 2, 3, 3] → 4: three pairs of 2 and one pair of 3. At most 100,000 values.

Hint and worked solution

When a value has appeared k times already, the new occurrence creates exactly k new pairs. Counting these incrementally avoids generating every pair.

static long matchingPairs(int[] a) {
    Map<Integer, Integer> seen = new HashMap<>();
    long pairs = 0;
    for (int x : a) {
        int previous = seen.getOrDefault(x, 0);
        pairs += previous;
        seen.put(x, previous + 1);
    }
    return pairs;
}

Expected O(n) time, O(n) extra space. [] → 0, [1, 2] → 0, [7, 7, 7, 7] → 6. For 100,000 identical values the answer is 4,999,950,000, which needs long.

  • Solve J7 without nested loops or double-counting pairs.

J8 — Best non-adjacent reward

Choose a subset of non-negative rewards with no two adjacent indices. Return the largest total; choosing none is allowed. At most 100,000 rewards, each at most 1 billion. [2, 7, 9, 3, 1] → 12 by selecting 2, 9, 1. This original exercise teaches the same include/skip pattern as House Robber, which one internship report named.

Hint and worked solution

For the first i rewards, either skip the last (best[i-1]) or take it plus the best ending before its neighbor (best[i-2] + value). Keep only the previous two totals. Greedily taking the larger immediate neighbor fails on [2, 3, 2], whose best is 4.

static long bestReward(int[] rewards) {
    long twoBack = 0, oneBack = 0;
    for (int reward : rewards) {
        long current = Math.max(oneBack, twoBack + reward);
        twoBack = oneBack;
        oneBack = current;
    }
    return oneBack;
}

O(n) time, O(1) extra space. Test [] → 0, [5] → 5, [2, 3, 2] → 4, [0, 0] → 0, and [1000000000, 0, 1000000000, 0, 1000000000] → 3000000000.

  • Solve J8 and explain both recurrence choices before coding.

Targeted resources

  • Dev.java learning paths: use Language Basics for loops, arrays, operators, and strings; use Collections for maps and sets. Skip deployment and JVM deep dives for this crash plan.
  • HackerRank Java: practise Java stdin/stdout, loops, and strings if the platform interface is unfamiliar. An account may be needed for submissions.
  • House Robber: an optional DP reattempt after J8; explain the recurrence without reading an editorial.

Readiness check: implement one array/string task from a blank file, test normal/empty/boundary cases, and explain the time and space costs. Then return to the crash plan and mocks.

On this page