Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
Big O for a loop vs a javasccript method that solves a problem

Find if the two arrays contain a similar property or value.

const one =[1,2,3,4,5]
const two = [5,6,7,8] 
// a double loop that solves this problem 
O(n^2)

VS

two.some(item => one.includes(item))
// this is more efficient than the double loop method 
// but behind the scenes isnt javascript just looping ?
// why is this more performant ? 
// and is the big O  of this O(n)? 
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If your

a double loop that solves this problem

breaks out of the loops as soon as a match is found, then both methods are similarly inefficient - they both require iterating over all of N elements M times, worst-case, where N is the length of one array and M is the length of the other. (So, O(n * m), or O(n^2), depending on how you want to specify the lengths of the inputs.)

The advantage to the second method

two.some(item => one.includes(item))

is that it's a lot more readable than using for loops. It's not more performant - the opposite is true, for loops are generally faster than array methods.

If you wanted to reduce the complexity to O(n), instead of iterating over the second array inside a loop, use a Set lookup inside the loop, which is much faster:

const oneSet = new Set(one);
return two.some(item => oneSet.has(item));

because set lookup is sublinear, and generally O(1) - resulting in an overall complexity of O(n).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!