jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
39 stars 5 forks source link

Two Sums #188

Closed jsartisan closed 2 hours ago

jsartisan commented 2 hours ago

Info

difficulty: easy
title: Two Sums
type: question
template: typescript
tags: javascript,blind75

Question

You are given an array of integers nums and an integer target. Write a function that returns the indices i and j such that nums[i] + nums[j] == target and i != j.

You can assume that each input will have exactly one pair of indices i and j that satisfy the condition.

Make sure to return the indices with the smaller index first.

Constraints:

Example Usage:

// Example 1
const nums1 = [3, 4, 5, 6];
const target1 = 7;
console.log(twoSum(nums1, target1)); // Output: [0, 1]

// Example 2
const nums2 = [4, 5, 6];
const target2 = 10;
console.log(twoSum(nums2, target2)); // Output: [0, 2]

// Example 3
const nums3 = [5, 5];
const target3 = 10;
console.log(twoSum(nums3, target3)); // Output: [0, 1]

Template

index.ts

export function twoSum(nums: number[], target: number): number[] {
 // your implementation code
}

index.test.ts

import { twoSum } from './index';

describe('twoSum function', () => {
  test('Example 1', () => {
    const nums = [3, 4, 5, 6];
    const target = 7;
    expect(twoSum(nums, target)).toEqual([0, 1]);
  });

  test('Example 2', () => {
    const nums = [4, 5, 6];
    const target = 10;
    expect(twoSum(nums, target)).toEqual([0, 2]);
  });

  test('Example 3', () => {
    const nums = [5, 5];
    const target = 10;
    expect(twoSum(nums, target)).toEqual([0, 1]);
  });

  test('Negative numbers', () => {
    const nums = [-3, 4, 3, 90];
    const target = 0;
    expect(twoSum(nums, target)).toEqual([0, 2]);
  });

  test('Different number order', () => {
    const nums = [1, 5, 7, 3, 8];
    const target = 10;
    expect(twoSum(nums, target)).toEqual([1, 3]);
  });
});
github-actions[bot] commented 2 hours ago

189 - Pull Request updated.