Longest Common Prefix - Leet Code Solution
Problem Statement Write a function to find the longest common prefix string…
September 13, 2019
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).
The obvious brute force algorithm. The key is to get the closest. You need to compare
Math.abs(target - calculated_sum)
Lets look at the optimized solution.
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;
}
Problem Statement Write a function to find the longest common prefix string…
Problem Statement Given n non-negative integers a1, a2, …, an , where each…
A Binary Search tree (BST) is a data structure which has two children nodes…
Graph Topological Sorting This is a well known problem in graph world…
Problem Statement You are given two non-empty linked lists representing two non…
Problem Statement Determine whether an integer is a palindrome. An integer is a…
In this post, we will see some of the frequently used concepts/vocabulary in…
System design interview is pretty common these days, specially if you are having…
Introduction You are given an array of integers with size N, and a number K…
Graph Topological Sorting This is a well known problem in graph world…
Problem Statement Given a Binary tree, print out nodes in level order traversal…
Problem Statement Given an array nums of n integers and an integer target, are…