~/coding-interview/leetcode-three-sum-closest.md

Three Sum Closest - Leet Code Solution

// TL;DR

Sort the array, then for each element use two pointers (left/right) to find the triplet sum closest to target. Track minimum absolute difference. O(n²).

Three Sum Closest - Leet Code Solution

Problem Statement

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Solution-1

The obvious brute force algorithm. The key is to get the closest. You need to compare

Math.abs(target - calculated_sum)

Solution-2

Lets look at the optimized solution.

  1. Sort the array
  2. Have left and right pointers.
  3. Keep calculating sum of three values.
  4. Compare absolute value of difference between targetSum and calculated sum.
  5. If sum is lesser, need to move left pointer
  6. else move right pointer.
public int threeSumClosest(int[] nums, int target) {
	Arrays.sort(nums);
	
	int l = nums.length;
	int minDiff = Integer.MAX_VALUE;
	int result = 0;
	for (int i=0; i<l; i++) {
		int j=i+1;
		int k=l-1;
		
		while (j < k) {
			int sum = nums[i] + nums[j] + nums[k];
			if (sum == target) return sum;
			else if (sum < target) j++;
			else k--;
			
			if (Math.abs(target - sum) < minDiff) {
				minDiff = Math.abs(target - sum);
				result = sum;
			}
		}
	}
	
	return result;
}

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Leetcode - Maximum Non Negative Product in a Matrix

Leetcode - Maximum Non Negative Product in a Matrix

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Leetcode - Split a String Into the Max Number of Unique Substrings

Leetcode - Split a String Into the Max Number of Unique Substrings

Problem Statement Given a string s, return the maximum number of unique…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…