HackerHeap

Leetcode 15 3 Sum

// 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:

  1. 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?”
  2. 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.”
  3. Ask for the upgrade. “Now show me the optimal solution. What insight makes it possible? What pattern is this an instance of?”
  4. 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.

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Solution 1:
public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> returnList = new ArrayList<List<Integer>>();
        if(nums==null||nums.length < 2) return returnList;
        Arrays.sort(nums);
        int length = nums.length;
        for(int i=0;i<length;i++){
            
            if(i>0 && nums[i]==nums[i-1]) continue;
            int j=i+1;
            int k=length-1;
            int target = 0 - nums[i];
            while(j<k){
                if(nums[j]+nums[k] == target){
                    returnList.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    while(j<k && nums[j]==nums[j+1]) j++;
                    while(j<k && nums[k]==nums[k-1]) k--;
                    j++;k--;
                }else if(nums[j]+nums[k] < target){
                    j++;
                }else{
                    k--;
                }
            }
        }
        return returnList;
    }
}

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.


Tagged: · · · · · · ·