Leet Code 1. Two Sum : Hey there, coding enthusiasts! Welcome back to another exciting coding session. Today’s problem is a treat—literally! We’re going to solve the “two sum ” or “Leet Code .1‘
Time Complexity:
- Brute-force: O(n^2)
- HashMap: O(n)
- Two Pass HashMap: O(n)
- Two Pointer: O(n log n)
JavaScript:
1. Brute Force Approach (JavaScript):
function twoSum(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
return []; // No solution found!
}
2. HashMap Approach (JavaScript):
function twoSum(nums, target) {
const numToIndex = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (numToIndex.has(complement)) {
return [numToIndex.get(complement), i];
}
numToIndex.set(nums[i], i);
}
return []; // No solution found!
}
3. Two Pass HashMap Approach (JavaScript):
var twoSum = function(nums, target) {
const numToIndex = {};
// First pass: Populate the object
for (let i = 0; i < nums.length; i++) {
numToIndex[nums[i]] = i;
}
// Second pass: Check for the complement
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (complement in numToIndex && numToIndex[complement] !== i) {
return [i, numToIndex[complement]];
}
}
return [];
};
4. Two-Pointer Approach (JavaScript):
function twoSum(nums, target) {
const numsWithIndex = nums.map((num, index) => [num, index]);
numsWithIndex.sort((a, b) => a[0] - b[0]);
let left = 0, right = nums.length - 1;
while (left < right) {
const sum = numsWithIndex[left][0] + numsWithIndex[right][0];
if (sum === target) {
return [numsWithIndex[left][1], numsWithIndex[right][1]];
} else if (sum < target) {
left++;
} else {
right--;
}
}
return []; // No solution found!
}
And there you have it! Four different programming languages, four approaches to solving the “Two Sum” problem, and hopefully a smile on your face as well! Remember, choosing the right approach depends on the specific requirements and constraints of your problem. Happy coding!