Java Coding Challenges with Explained Solutions

Java coding challenges are most useful when they specify a contract and require you to justify a solution.

Lesson 119 of 127Intermediate13 min read

Java coding challenges are most useful when they specify a contract and require you to justify a solution. The three problems here cover run-length encoding, first unique characters, and fixed-width window sums. Each includes a complete Java 17 solution, visible output, and the reasoning behind its time and storage costs. Attempt a simple correct solution first. Then compare approaches and improve the dominant work without changing the result contract or overlooking empty and invalid inputs.

Challenge one: encode consecutive letter runs

Given an ASCII-letter string, replace each consecutive run with the letter followed by its count. aaabbc becomes a3b2c1. An empty string becomes empty output. Nonadjacent equal letters form separate runs; aba becomes a1b1a1 rather than a2b1. Restricting the input to letters keeps the count notation unambiguous for this exercise. Arbitrary digit-containing data would need a clearly designed escape or structured representation for reversible encoding.

Plan the run boundaries

Track the first index of the current run and advance an end index while the letter matches. The run length is end minus start. Append the letter and length, then move start to end. Each character is visited as part of one run, giving linear time. StringBuilder avoids repeatedly creating a new accumulated String. Output size is linear in input size under this representation, and its storage should be included or separately stated in your space analysis.

Challenge two: locate the first unique character

For a lowercase ASCII input, return the index of the first character occurring exactly once, or minus one if none exists. The example swiss returns one because w occurs once and appears before the other unique character i. A two-pass solution first counts all letters, then scans the original order for a count of one. Returning the first map entry would be wrong if the map does not preserve input order.

Make the character model explicit

The solution uses Java char values and deliberately constrained lowercase ASCII input. General Unicode text can contain supplementary code points represented by surrogate pairs, so a char-based solution is not a complete user-perceived-character algorithm. Define whether a broader problem counts UTF-16 units, code points, or grapheme clusters before implementing it. The counting technique remains useful, but the iteration and index contract must match the chosen text model.

Challenge three: maximize a fixed-width sum

Given an integer array and a valid window width, return the greatest sum of exactly that many consecutive values. For four, minus one, two, seven, minus three with width three, the window sums are five, eight, and six. The answer is eight. Negative values are allowed, so initializing the best sum to zero would be wrong for all-negative input. A long accumulator avoids int overflow when summing several int values.

Slide the window instead of recomputing it

Compute the first window once. For each later position, add the incoming value and subtract the value leaving the window. That updates the sum in constant work per position, making the full algorithm linear rather than recomputing every width-length sum. Reject width zero, negative width, and width larger than the array before accessing elements. Explain the invariant that the current sum always represents exactly the most recent window.

Practice tasks and checks

Test encoding with empty input, a single letter, a long identical run, and alternating letters. Test uniqueness with all repeated letters and a unique letter at the final position. For the window problem, test width one, width equal to the array length, all-negative input, and invalid width. Write a simple recomputing implementation as an independent oracle for short arrays, then compare it with the sliding solution over several inputs. Explain both time costs and the unchanged result contract. Finally, decide whether to support broader Unicode text or delimiter-containing input before changing the first two algorithms. Do not silently extend representation assumptions merely because a new example looks similar.

Java Summary

  • Define input and output contracts before optimizing.
  • Preserve source order when the result asks for the first occurrence.
  • Initialize extrema from real candidates when negative values are allowed.
  • Continue with complexity analysis when these examples are clear.

Java Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Encode each consecutive run

Save this program as RunChallenge.java. Compile it with javac RunChallenge.java and run it with java RunChallenge.

Expected output:

The first run begins at zero and ends before index three, giving three a characters. The next run contains two b characters and the last contains one c. For aba, each next character differs, so every run has length one. start always advances to a larger end, ensuring termination. The method expects non-null input satisfying the documented letter-only contract; a public application boundary should validate that contract.

Java
public class RunChallenge {
    static String encode(String text) {
        StringBuilder result = new StringBuilder();
        int start = 0;
        while (start < text.length()) {
            int end = start + 1;
            while (end < text.length() && text.charAt(end) == text.charAt(start)) end++;
            result.append(text.charAt(start)).append(end - start);
            start = end;
        }
        return result.toString();
    }
    public static void main(String[] args) {
        System.out.println(encode("aaabbc"));
        System.out.println(encode("aba"));
    }
}
Output
a3b2c1
a1b1a1
Example 2

Find uniqueness while retaining input order

Save this program as UniqueChallenge.java. Compile it with javac UniqueChallenge.java and run it with java UniqueChallenge.

Expected output:

The count pass records three s characters, one w, and one i for swiss. The ordered second pass rejects index zero because s repeats, then returns index one for w. aabb has no count of one, so the final fallback is minus one. Scanning the source rather than HashMap's entries preserves the meaning of first. Under the bounded alphabet, stored distinct-count entries are bounded too.

Java
import java.util.HashMap;
import java.util.Map;
public class UniqueChallenge {
    static int firstUnique(String text) {
        Map<Character, Integer> counts = new HashMap<>();
        for (char letter : text.toCharArray()) counts.merge(letter, 1, Integer::sum);
        for (int i = 0; i < text.length(); i++) {
            if (counts.get(text.charAt(i)) == 1) return i;
        }
        return -1;
    }
    public static void main(String[] args) {
        System.out.println(firstUnique("swiss"));
        System.out.println(firstUnique("aabb"));
    }
}
Output
1
-1
Example 3

Compute the best window sum

Save this program as WindowChallenge.java. Compile it with javac WindowChallenge.java and run it with java WindowChallenge.

Expected output:

The first input starts with sum five, slides to eight, then to six, retaining eight. The second has sums minus seven and minus ten, so the answer is minus seven rather than an invented zero. Initializing best from the first actual window handles this correctly. Adding and subtracting separately with a long accumulator avoids first overflowing an int expression for the incoming-minus-outgoing difference.

Java
public class WindowChallenge {
    static long maximum(int[] values, int width) {
        if (width <= 0 || width > values.length) throw new IllegalArgumentException("Invalid width");
        long current = 0;
        for (int i = 0; i < width; i++) current += values[i];
        long best = current;
        for (int i = width; i < values.length; i++) {
            current += values[i];
            current -= values[i - width];
            best = Math.max(best, current);
        }
        return best;
    }
    public static void main(String[] args) {
        System.out.println(maximum(new int[]{4, -1, 2, 7, -3}, 3));
        System.out.println(maximum(new int[]{-5, -2, -8}, 2));
    }
}
Output
8
-7

Java FAQ

Must a challenge solution be the shortest?

No. Prefer a correct contract, clear invariant, and suitable complexity. Short source can hide invalid assumptions or overflow. Improve code after you can explain why it produces the required result.

Should I mention input restrictions in an interview?

Yes. Clarify null, empty input, duplicates, character representation, and size limits when they affect the algorithm. A stated precondition is useful only if it matches the requested problem rather than silently simplifying it.

How should I approach a coding challenge?

Restate the problem and its constraints, work through two or three small examples by hand, and write a simple correct solution first. Then look for repeated work you can remove, and finally test edge cases such as empty input, one element and the largest allowed values.

What is the sliding window technique?

A way to process every fixed-size or growing range of an array without recomputing each from scratch. When the window moves one step, add the value entering it and subtract the value leaving it. It turns many O(n × k) problems into O(n) ones.

Where can I practise more Java coding challenges?

Sites such as LeetCode, HackerRank, Codewars and Exercism offer thousands of problems with automatic tests, and many support Java. Mix easy problems for speed with harder ones that teach new techniques, and review other people's solutions after solving each one.

Java Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

How does the run encoder represent aba?

Multiple choicemedium

Why scan the original text in the unique-character second pass?

Java Quiz

2 questions to check what you learned.

  1. What is the best width-two sum for -5, -2, -8?

    • -7
    • 0
    • -2
  2. Which update slides a fixed-width sum?

    • Add the incoming value and subtract the outgoing value
    • Sort every window
    • Reset to zero every time