Leetcode 2 Add Two Numbers Java Solution
// SOLVING THIS WITH AN AI ASSISTANT (2026)
If you are working through this problem with an AI coding assistant — Claude, ChatGPT, Cursor chat, Gemini, GitHub Copilot, Aider, or any agent — the goal isn’t to ask for the answer. It is to use the tool to understand the pattern. The prompt sequence I’d run:
- Spec it back to me first. “In your own words, what is this problem actually testing? What’s the smallest example that fails the naive approach?”
- Brute-force first, optimize after. “Write the simplest correct solution, even if it’s O(n²). Don’t optimize. Just make it correct, with comments explaining each step.”
- Ask for the upgrade. “Now show me the optimal solution. What insight makes it possible? What pattern is this an instance of?”
- Stress-test it. “Generate 10 edge cases — empty input, single element, duplicates, max size, sorted, reverse-sorted. Run my solution against each.”
The pattern matters more than the answer. If the agent just hands you optimized code, you’ve trained yourself to lose interviews.
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. Solution 1:
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null) return null;
Queue<Integer> s1 = new LinkedList<Integer>();
Queue<Integer> s2 = new LinkedList<Integer>();
ListNode returnNode = null;
ListNode firstNode = null;
int carry = 0;
while(l1!=null){
s1.add(l1.val);
l1 = l1.next;
}
while(l2!=null){
s2.add(l2.val);
l2 = l2.next;
}
while(s1.peek()!=null || s2.peek()!=null){
int s1pop = 0;
int s2pop = 0;
if(s1.peek()!=null){
s1pop = (Integer)s1.remove();
}
if(s2.peek()!=null){
s2pop = (Integer)s2.remove();
}
int total = s1pop + s2pop + carry;
if(total >= 10){
carry = total/10;
ListNode n = new ListNode(total%10);
if(returnNode == null){
returnNode = n;
firstNode = returnNode;
}else{
while(returnNode.next!=null){
returnNode= returnNode.next;
}
returnNode.next = n;
}
}else{
carry = 0;
ListNode n2 = new ListNode(total);
if(returnNode == null){
returnNode = n2;
firstNode = returnNode;
}else{
while(returnNode.next!=null){
returnNode= returnNode.next;
}
returnNode.next = n2;
}
}
}
if(carry!=0){
ListNode carryNode = new ListNode(carry);
while(returnNode.next!=null){
returnNode = returnNode.next;
}
returnNode.next = carryNode;
}
return firstNode;
}
}
For the AI-native engineering side of HackerHeap — building MCP servers, comparing agents (Claude Code, Cursor, Windsurf, Codex, Gemini, Copilot), and weekly working code — see the Friday Build newsletter and the MCP archive.