Hello. In the previous lesson, you selected Java collections by matching the problem’s required behavior to the dominant operation cost: HashMap for key-associated lookup, ArrayDeque for endpoint work, and ArrayList for indexed sequences. Now the focus shifts from choosing an algorithm to expressing one accurately in Java.
In a coding screen, the interviewer often accepts a method-level solution rather than a complete application. The task is to translate a settled plan into code with correct types, method calls, loop boundaries, and return behavior—without autocomplete quietly repairing syntax or suggesting APIs. By the end of this lesson, you will have a repeatable way to turn interview pseudocode into a correct Java method.
Treat implementation as a controlled translation
Pseudocode is deliberately flexible. It can say “create an empty map,” “check whether the key exists,” or “return the two indices.” Java requires you to settle details that pseudocode leaves implicit:
- What are the exact input and output types?
- What concrete collection implementation will be created?
- Is the loop’s upper boundary inclusive or exclusive?
- Which API method corresponds to “contains”?
- What must happen when no result is found?
- Which variables are declared inside the loop, and which must survive after it?
A reliable coding order is:
- Preserve the platform’s contract. Use the requested method name, parameter types, and return type exactly.
- Write a compiling frame. Create the class and method braces before filling in algorithmic detail.
- Translate one pseudocode statement at a time. Do not redesign the algorithm while typing.
- Perform a manual compiler pass. Check names, types, delimiters, and API spelling.
- Trace one ordinary case and one edge-shaped case. The next lesson will develop test design in depth; here, the goal is to catch translation mistakes promptly.
This separation matters. If the algorithm is already sound, implementation should be a precise conversion job—not another round of problem solving.
How To Pass Coding Interviews Like the Top 1%
Watch “How To Pass Coding Interviews Like the Top 1%” by Tech With Tim for practical guidance on the implementation phase. The key idea is that once the approach is decided, your job is to make your code readable, deliberate, and visible to the interviewer.
Watch the coding phase for advice on narrating the next implementation step, choosing descriptive names, and keeping code easy to follow. Then watch fluency practice for the case for practicing core syntax without predictive tools or an IDE.
A useful interview narration is brief and concrete:
“I have the one-pass hash-map plan. I’ll first write the required method signature, then initialize the map, scan the array by index, check for a previously seen complement, and finally return the indices.”
That statement gives the interviewer a map of the code they are about to read. You do not need to narrate every keystroke.
Build the Java frame before the algorithm
A Java interview solution begins with a method declaration. Think of it as an agreement with the caller: the caller supplies values with the listed parameter types, and your method returns exactly the declared type.
Read “Defining Methods” from Dev.java to reinforce the fixed structure of a Java method declaration. In an interview, this structure is worth knowing well enough to produce without prompts.
In the “Defining a Method” section, begin with the method components. Read through the six-part list, focusing on the return type, typed parameter list, and braced body. Then read the short “Naming a Method” section: method names conventionally begin with a lowercase verb, such as findPair or isPalindrome.
Suppose an interview platform provides this contract:
public int[] twoSum(int[] nums, int target)
Before writing the solution, read it literally:
| Part | Meaning |
|---|---|
public | The platform must be able to call the method. Keep it if supplied. |
int[] | Return an array of primitive integers, not a List<Integer>. |
twoSum | Use this exact name; Java is case-sensitive. |
int[] nums | The input is an array, so indexed access and nums.length are available. |
int target | The target is a primitive integer. |
A typical online-judge frame is:
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
// implementation goes here
}
}
Some platforms provide the class, imports, or method signature for you. In that case, do not rewrite or alter what the platform supplies. In particular, do not add static, change int[] to List<Integer>, or replace the requested method name with one you prefer. Those may be valid Java choices in another setting, but they violate the interface being tested.
The method’s name should be descriptive and camel-cased. In interview code, indexByValue tells the reader much more than map, and complement tells them more than x.
Translate a complete pseudocode plan: Two Sum
Consider this settled algorithm:
function twoSum(nums, target):
create an empty map from value to index
for i from 0 through nums.length - 1:
complement = target - nums[i]
if map contains complement:
return the stored index for complement and i
store nums[i] with index i in map
return an empty integer array
The important logical choice is the order of the last two steps. We check first and store the current value afterward. That prevents the current element from matching itself.
Before translating, make the implicit choices explicit:
| Pseudocode idea | Java translation | Why |
|---|---|---|
| Empty map from value to index | Map<Integer, Integer> indexByValue = new HashMap<>(); | The key is an array value; the associated value is its index. |
| “For from 0 through last index” | for (int i = 0; i < nums.length; i++) | Java array indices start at 0, and the last valid index is nums.length - 1. |
| Current array value | nums[i] | Array access requires square brackets and an integer index. |
| Map contains a key | indexByValue.containsKey(complement) | containsKey expresses the exact condition. |
| Get stored index | indexByValue.get(complement) | The stored Integer is automatically unboxed to int when placed in the result array. |
| Return two indices | return new int[] {storedIndex, i}; | The method contract requires int[]. |
| Store the value and its index | indexByValue.put(nums[i], i); | put associates a key with a value. |
Java arrays are zero-indexed. The array-index diagram below shows why an array of length 10 has valid indices from 0 to 9, rather than 1 to 10.

Here is the direct Java translation:
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> indexByValue = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (indexByValue.containsKey(complement)) {
return new int[] {indexByValue.get(complement), i};
}
indexByValue.put(nums[i], i);
}
return new int[0];
}
}
Notice what this code does not do:
- It does not sort
nums, which would change index meanings unless extra bookkeeping were added. - It does not test
indexByValue.get(complement) != null; the intended question is whether the key exists, socontainsKeyis clearer and more general. - It does not convert the array into a list. The input is already well suited to indexed traversal.
- It does not add a null-handling policy that the prompt did not specify. Clarify such requirements before coding rather than inventing behavior silently.
The final return new int[0]; has two roles. It gives Java a return value on the path where no pair is found, and it satisfies the compiler’s requirement that an int[] method returns an array on every possible control-flow path. If a specific problem guarantees exactly one answer, that line is unreachable for valid input, but it remains a conventional way to complete the method.
Preserve the array boundary exactly
A frequent translation error is:
for (int i = 0; i <= nums.length; i++) {
This attempts to access nums[nums.length] on the final iteration. That index does not exist. For an array with length , the valid index range is from through . In the standard Java loop form, that becomes:
for (int i = 0; i < nums.length; i++) {
The < is not stylistic. It encodes the boundary invariant that i is always a valid index when the body executes.
Know the small set of control-flow forms cold
Most interview pseudocode becomes a compact set of Java structures: if, for, while, return, and occasionally break or continue. You do not need unusual syntax to write strong interview code.
Control Flow Statements - Dev.java
Read the relevant parts of Dev.java’s “Control Flow Statements.” Focus on translating decisions, loops, and early returns accurately rather than on uncommon language features.
In “The If-Then Statement” and “The If-Then-Else Statement,” read the explanation of conditional execution and the warning beginning braces and branches. Use braces in interview code even for a one-line body. In “The For Statement,” read the loop components, paying close attention to initialization, termination, increment, and loop-variable scope. Finally, read the entire “Return Statement” subsection in the later “Continue Statement” section to reinforce that return exits the current method and must match its declared return type.
Here are the forms worth being able to produce unaided:
if (condition) {
// execute only when condition is true
} else {
// execute when condition is false
}
for (int i = 0; i < length; i++) {
// use i
}
while (condition) {
// repeat while condition remains true
}
return value;
Two habits prevent many silent mistakes:
- Always use braces. They make later edits safe and show exactly which statements belong to a condition or loop.
- Prefer an early return when the answer is final. In Two Sum, finding a valid pair completes the task. Returning immediately avoids extra state such as
found,firstIndex, andsecondIndex.
Use break only when you need to leave a loop but continue the method afterward. Use return when you are finished with the whole method. Confusing the two can leave a method running with incomplete state.
Perform a manual compiler pass
Without an IDE, do not depend on visual squiggles to find errors. Read the completed code once as though you are the Java compiler. This takes roughly a minute and is more reliable than hoping a final test catches a spelling or type error.
1. Check every declaration
For each variable, verify this pattern:
Type variableName = expression;
In the Two Sum solution:
Map<Integer, Integer> indexByValue = new HashMap<>();
int complement = target - nums[i];
Ask whether the expression produces the declared type. target - nums[i] is an int, so int complement is correct. new HashMap<>() creates a map, so it can be assigned to a Map<Integer, Integer> reference.
2. Check method names and capitalization
Java is case-sensitive. These are different identifiers:
HashMap
Hashmap
hashMap
Only the first is the class name. Likewise, the key map operations are:
indexByValue.containsKey(complement);
indexByValue.get(complement);
indexByValue.put(nums[i], i);
Memorize this small repertoire rather than improvising names such as contains, find, or insert, which are not Map methods.
3. Check delimiters and semicolons
A quick visual scan should match every opening delimiter with a closing one:
- Parentheses belong around method parameters,
ifconditions, andforcomponents. - Square brackets belong in array types and array access.
- Curly braces form method, conditional, and loop bodies.
- Semicolons end declarations, assignments, method-call statements, and
returnstatements.
Do not put a semicolon after an if or for header:
if (indexByValue.containsKey(complement)) {
return new int[] {indexByValue.get(complement), i};
}
A stray semicolon immediately after an if creates an empty conditional body, which can produce code that compiles but behaves incorrectly.
4. Check scope and state order
A variable declared inside the loop cannot be used after its closing brace:
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
}
// complement is unavailable here
Then verify that statements appear in the same meaningful order as the pseudocode. For Two Sum, this ordering is essential:
if (indexByValue.containsKey(complement)) {
return new int[] {indexByValue.get(complement), i};
}
indexByValue.put(nums[i], i);
If put occurred first, a one-element input such as {3} with target 6 could incorrectly appear to match index 0 with itself.
Trace the translation, not just the final answer
A short trace checks whether your Java variables carry the intended meaning. Use:
nums = {2, 7, 11, 15}
target = 9
| Loop index | nums[i] | complement | Map before check | Result |
|---|---|---|---|---|
| 0 | 2 | 7 | empty | No 7 stored; record 2 at index 0 |
| 1 | 7 | 2 | {2=0} | Find 2; return {0, 1} |
This confirms several facts at once:
- The loop begins at the first index.
- The complement is computed before it is used.
- The map stores values as keys and indices as values.
- The returned values are indices, not the numbers
2and7. - The map is updated only after the lookup.
A five-minute fluency routine can make this mechanical:
- Hide the completed Java code, but leave the pseudocode visible.
- In a plain text editor or on paper, write the imports, class, and method signature.
- Translate each pseudocode line without looking up completion suggestions.
- Compare your code with the reference only after finishing.
- Record the category of any miss: API spelling, type, delimiter, loop boundary, or return type.
Correcting a small, recurring category is far more effective than merely retyping a finished answer.
Key takeaways
Writing Java from pseudocode is a disciplined translation process:
- Preserve the interviewer’s required method signature exactly.
- Build the method frame first, then translate the algorithm statement by statement.
- Make pseudocode details explicit: types, collection APIs, loop boundaries, and fallback returns.
- For an indexed array loop, use
i < nums.length;nums.lengthitself is never a valid index. - Use familiar, readable Java constructs and descriptive names rather than clever syntax.
- Run a manual compiler pass for types, method spelling, braces, semicolons, scope, and statement order.
- Trace a concrete input to verify that the Java state means what the pseudocode intended.
Next, you will turn testing from an informal final check into a systematic interview skill by constructing boundary, invalid, and adversarial cases for a proposed algorithm.
Can't find a good explanation? Sign up and we'll make it for you
Sign up