LeetCode: Two Sum II - Input array is sorted Solution

If trying to explain takes time, go on
1var twoSum = function (numbers, target) {
2 const n = numbers.length
3 let lo = 0
4 let hi = n - 1
5
6 while (true) {
7 const sum = numbers[lo] + numbers[hi]
8
9 if (sum === target) {
10 return [lo + 1, hi + 1]
11 } else if (sum < target) {
12 lo++
13 } else if (sum > target) {
14 hi--
15 }
16 }
17}

Comments

Loading comments...

Tags

leetcode

array

two pointers

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

CodeWars: Snail

Keep going in a way

Previous Post

LeetCode: First Bad Version

Luckily, mid calculation in JS did not throw overflow error

HoningJS

Search Posts