
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Two sum problem in linear time in JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first argument and a target sum as the second argument.
The function should find and return the index of two such numbers from the array (consecutive or non−consecutive) that adds up to give the target sum (if there are any). The condition is that we have to do this in linear time (one iteration).
We will keep count of the iterated numbers using a map, and if at any point we encounter two numbers that give the target sum we return right away.
Example
The code for this will be −
const arr = [1, 3, 5, 7, 9, 11]; const target = 16; const twoSum = function(arr, target) { const map = new Map(); for(let i = 0; i < arr.length; i++) { let num = arr[i]; if(map.get(num) === undefined){ map.set(target−num, i) }else{ return [map.get(num), i] }; }; }; console.log(twoSum(arr, target));
Output
And the output in the console will be −
[3, 4]
- Related Articles
- Maximum products of two integers in linear time in JavaScript
- Combination sum problem using JavaScript
- Problem: Time taken by tomatoes to rot in JavaScript
- Find first duplicate item in array in linear time JavaScript
- Two sum in BSTs in JavaScript
- Subset Sum Problem
- Snail Trail Problem in JavaScript
- Recursive Staircase problem in JavaScript
- Distributing Bananas Problem in JavaScript
- Reverse sum of two arrays in JavaScript
- Multiply and Sum Two Arrays in JavaScript
- Recursion problem Snail Trail in JavaScript
- Expressive words problem case in JavaScript
- 2 Key keyboard problem in JavaScript
- Meeting Rooms 2 problem in JavaScript

Advertisements