Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Added the new algorithm TwoSum using array in Data Structure #1854

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
codewithRakshita wants to merge 1 commit into TheAlgorithms:master
base: master
Choose a base branch
Loading
from codewithRakshita:my-feature
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Data-Structures/Array/TwoSum.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* This function will accept an array and a target value,
* and return the indexes of the two numbers that add up to the target.
* If no such pair exists, it returns null.
* @param {number[]} nums - array of numbers
* @param {number} target - target sum
* @returns {number[] | null} - array containing two indexes or null
*/

const 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 null
}

export { twoSum }
33 changes: 33 additions & 0 deletions Data-Structures/Array/test/TwoSum.test.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { twoSum } from '../TwoSum'

describe('twoSum tests', () => {
it('should return indices for a normal case', () => {
const nums = [2, 7, 11, 15]
const target = 9
expect(twoSum(nums, target)).toEqual([0, 1])
})

it('should return indices when pair is in middle', () => {
const nums = [1, 4, 6, 8, 5]
const target = 11
expect(twoSum(nums, target)).toEqual([2, 4])
})

it('should handle negative numbers', () => {
const nums = [-3, 4, 3, 90]
const target = 0
expect(twoSum(nums, target)).toEqual([0, 2])
})

it('should return null if no pair found', () => {
const nums = [1, 2, 3, 4]
const target = 100
expect(twoSum(nums, target)).toBeNull()
})

it('should work with duplicate numbers', () => {
const nums = [3, 3]
const target = 6
expect(twoSum(nums, target)).toEqual([0, 1])
})
})
Loading

AltStyle によって変換されたページ (->オリジナル) /