3Sum Closest - Step-by-Step with Java

I am a developer who loves Java, Spring, Quarkus, Micronaut, Open source, Microservices, Cloud
Search for a command to run...

I am a developer who loves Java, Spring, Quarkus, Micronaut, Open source, Microservices, Cloud
No comments yet. Be the first to comment.
Data Structure & Algorithms : the most important and fundamental of any programmer. We will explore famous questions on datastructure & algorithms from various popular websites.
Question Link : https://leetcode.com/problems/simplify-path/ After reading the question , the first intution is for using stack as appropriate data structure There are two possiblities either you do interate character by character or split the str...
Spring AI Tool Calling: From Chatbot to AI Agent with @Tool Your AI is smart. It knows an enormous amount. But it's frozen. It doesn't know what time it is right now. It doesn't know what's on your ca
Spring AI Advisors API Explained Series: Spring AI Complete Course — Lecture 4 of 12Reading Time: 8 minutesLevel: Intermediate Most developers stop at ChatClient. That is enough for demos. It is not
Working with Multiple AI Models in Spring AI Spring AI Complete Course — Lecture 3 of 12Previous: Lecture 2 — ChatClient API | Next: Lecture 4 — Advisors API In production AI applications, you rarel
Spring AI ChatClient API: The Fluent Heart of AI Integration Introduction If you've ever tried integrating AI models into a Java application, you know the pain. HTTP clients, API keys scattered everywhere, vendor-specific SDKs that never quite fit. W...
What is Spring AI? — Why Java Developers Need This in 2026 Every AI tutorial you see is in Python. LangChain, LlamaIndex, OpenAI SDK — all Python. But here's the uncomfortable truth: 80% of enterprise backends run Java. So who's building AI into thos...
The problem asks us to find three numbers in an array whose sum is closest to a given target value.
Example Input: nums = [-1, 2, 1, -4], **target = 1 **Expected Output**:2`
We can solve the problem using the Two Pointer Technique with a sorted array. Here's a high-level summary of the solution:
Sort the array to prepare for the two-pointer method.
Iterate through each number in the array. For each number:
Fix the number as the first number (nums[start]).
Use two pointers, left and right, to explore the remaining numbers.
Calculate the sum of the three numbers.
Update the closest sum whenever the new sum is closer to the target than the previous closest value.
Adjust the pointers (left++ or right--) based on the comparison between sum and target.
Here is the final Java solution:
import java.util.Arrays;
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums); // Step 1: Sort the array
int closest = Integer.MAX_VALUE; // Closest sum initialized to max value
for (int i = 0; i < nums.length; i++) {
int start = i; // Fix the current number
int left = i + 1; // Left pointer
int right = nums.length - 1; // Right pointer
while (left < right) { // Step 2: Two-pointer approach
int sum = nums[start] + nums[left] + nums[right];
// Step 3: Update closest sum
if (Math.abs(sum - target) < Math.abs(closest - target)) {
closest = sum;
}
if (sum == target) return sum; // Perfect match
// Move pointers
if (sum < target) {
left++; // Increase the sum
} else {
right--; // Decrease the sum
}
}
}
return closest; // Return the closest sum
}
}
We will use the input nums = [-1, 2, 1, -4] and target = 1.
The input array becomes:
cssCopy codeSorted nums = [-4, -1, 1, 2]
You can use a diagram to visualize this:
Image 1: Array before and after sorting
Original: [-1, 2, 1, -4]
Sorted: [-4, -1, 1, 2]
We loop through the array, starting with i = 0:
start = i = 0 → nums[start] = -4
left = 1 → nums[left] = -1
right = 3 → nums[right] = 2
Initial pointers:
codenums = [-4, -1, 1, 2]
↑ ↑ ↑
start left right
First sum = nums[start] + nums[left] + nums[right] = -4 + (-1) + 2 = -3
Compare |target - sum|:
target = 1
difference = |1 - (-3)| = 4
Update closest to -3 because it's the first valid sum.
Image 2: State after the first calculation
codeSum = -3
Closest = -3
Since sum < target, we increment left:
left = 2 → nums[left] = 1New pointers:
codenums = [-4, -1, 1, 2]
↑ ↑ ↑
start left right
New sum = -4 + 1 + 2 = -1
Compare |target - sum|:
difference = |1 - (-1)| = 2Update closest to -1 because it's closer to the target than -3.
Image 3: State after the second calculation
Sum = -1
Closest = -1
Since sum < target, increment left:
left = 3 → Now left equals right, so the while loop ends.Now, i = 1:
start = 1 → nums[start] = -1
left = 2 → nums[left] = 1
right = 3 → nums[right] = 2
New pointers:
nums = [-4, -1, 1, 2]
↑ ↑ ↑
start left right
Sum = -1 + 1 + 2 = 2
Compare |target - sum|:
difference = |1 - 2| = 1Update closest to 2 because it's closer than -1.
Image 4: State after final calculation
codeSum = 2
Closest = 2
The loop ends, and the closest sum is returned as 2.
With clear visuals and diagrams at each step, you can demonstrate how the pointers move and how the closest sum is updated. Here’s a summary of the pointer movements and sums:
| Iteration | start | left | right | Sum | Closest |
| 1 | -4 | -1 | 2 | -3 | -3 |
| 2 | -4 | 1 | 2 | -1 | -1 |
| 3 | -1 | 1 | 2 | 2 | 2 |
Closest Sum = 2