May 30th 2023

Two Sum — Typescript

Problem Description permalink

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= 109 Only one valid answer exists.

Solution permalink

// Util functions
function expect(description: string, test: boolean) {
if (test) {
console.log(`${description}`)
} else {
console.log(`${description}`)
}
}

function arrayEqual(a: number[], b: number[]): boolean {
if (a.length !== b.length) {
return false
}

for (var i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false
}
}

return true
}

// Problem
function twoSum(nums: number[], target: number): number[] {
for (var firstIndex = 0; firstIndex < nums.length; firstIndex++) {
const firstValue = nums[firstIndex];
for (var secondIndex = firstIndex + 1; secondIndex < nums.length; secondIndex++) {
const secondValue = nums[secondIndex];

if (firstValue + secondValue === target) {
return [firstIndex, secondIndex];
}
}
}
return [-1, -1]
};


// Tests
expect("Looking for 9 in [2, 7, 11, 15]", arrayEqual(twoSum([2, 7, 11, 15], 9), [0, 1]))
expect("Looking for 6 in [3, 2, 4]", arrayEqual(twoSum([3, 2, 4], 6), [1, 2]))
expect("Looking for 6 in [3,3] (don't return same index)", arrayEqual(twoSum([3, 3], 6), [0, 1]))

// Output
/*
✅ Looking for 9 in [2, 7, 11, 15]
✅ Looking for 6 in [3, 2, 4]
✅ Looking for 6 in [3,3] (don't return same index)
*/

Discussion permalink

This is a brute force solution that optimizes for clarity of code and readability.

I also needed a small test tool. I find in toy problems that I'm often dropping in a tiny bit of functionality to make sure things work as expected.