search
HomeWeb Front-endJS TutorialAlgorithms that are easy to encounter in JS interviews

Algorithms that are easy to encounter in JS interviews

This time I will bring you algorithms that are easy to encounter in JS interviews. The following is a practical case, let’s take a look.

Recommended related articles:The most complete collection of js interview questions in 2020 (latest)

Prime numbers

Q: How would you verify a prime number?

A: A prime number can only be divisible by itself and 1. So, I'm going to run a while loop and add 1. (Look at the code examples. If you can’t understand it, it’s not your cup of tea. Go back and learn the javaScript basics first and then come back.)

Method 1

function isPrime(n){
 var pisor = 2;
 while (n > pisor){
 if(n % pisor == 0){
  return false; 
 }
 else
  pisor++;
 }
 return true;
}
isPrime(137); // = true
isPrime(237); // = false

Q: Can you do better?

A: Yes. The divisor increases by one at a time. After 3 I can add 2. If a number is divisible by any even number, it will be divisible by 2.

Supplement: If you don’t need to increase the divisor to this number. You can stop earlier. Let me explain it in the steps below (you can read it a few more times if you need to)

Step one, no number is divisible by a number greater than half of it. For example, 13 will never be divisible by 7,8,9...it can even be half of an even number. For example, 16 will be divisible by 8, but never by 9, 10, 11, 12...
Conclusion: A number will never be divisible by a number greater than half its value. So, we can loop 50% less.

Second step, now, if a number is not divisible by 3. (If it's divisible by 3, then it's not prime). Then, it is not divisible by any number greater than 1/3 of its value. For example, 35 is not divisible by 3. Therefore, it will never be divisible by a number greater than 35/3, never divisible by 12, 13, 14... If you take an even number like 36, it will never be divisible by 13, 14, 15.

Conclusion: A number is divisible by one-third of its value.

Step 3, for example, you have a number 127. 127 is not divisible by 2, so you should check at most 63.5. Secondly, 127 is not divisible by 3. So you will check to 127/3 approximately 42. It is not divisible by 5, the divisor should be less than 127/5 which is about 25, not 7. So, where do we stop?
Conclusion: The divisor will be less than math.sqrt(N)

Method 2

Don’t worry if you can’t understand it, just leave it alone. It doesn't matter if you're not a researcher.

function isPrime(n)
{
 var pisor = 3, 
  limit = Math.sqrt(n);
 //check simple cases
 if (n == 2 || n == 3)
  return true;
 if (n % 2 == 0)
  return false;
 while (pisor <p style="text-align: left;"><span style="color: #ff0000"><strong>Prime factors</strong></span></p><p style="text-align: left;">Q: How to find all the prime factors of a number? <br>A: Execute a while loop. Start dividing by 2. If it cannot be divided, record the divisor until completed. </p><pre class="brush:php;toolbar:false">function primeFactors(n){
 var factors = [], 
  pisor = 2;
 while(n>2){
 if(n % pisor == 0){
  factors.push(pisor); 
  n= n/ pisor;
 }
 else{
  pisor++;
 }  
 }
 return factors;
}
 primeFactors(69); // = [3, 23]

Q: What is the running time complexity? Can you do better?

A: O(n). You can start the divisor from 3 and add up to 2. Because, if a number is divisible by any even number, it will be divisible by 2. Therefore, you don't need to divide by even numbers. Furthermore, you won't have a factor larger than half its value. If you want to make it complicated, use the supplementary concepts from the first question.

Fibonacci (Fibonacci)

Q: How to get the nth Fibonacci number?
A: I create an array and start by iterating.

The Fibonacci series is one of the most popular interview questions for beginners. So, you have to learn this one.

Method 1

function fibonacci(n){
 var fibo = [0, 1];
 if (n <p style="text-align: left;">Q: What is the running time complexity? </p><p style="text-align: left;">A: O(n);</p><p style="text-align: left;">Q: Can you make it <a href="http://www.php.cn/wiki/80.html" target="_blank">recursive</a>? </p><p style="text-align: left;"><strong>Method 2</strong></p><pre class="brush:php;toolbar:false">function fibonacci(n){
 if(n <p style="text-align: left;">Q: What is the running time complexity? <br>A: O(2n); Details about time complexity</p><p style="text-align: left;"><span style="color: #ff0000"><strong>Greatest common divisor</strong></span></p><p style="text-align: left;">Q: How would you find two What is the greatest common divisor of numbers? </p><pre class="brush:php;toolbar:false">function greatestCommonpisor(a, b){
 var pisor = 2, 
  greatestpisor = 1;
 //if u pass a -ve number this will not work. fix it dude!!
 if (a = pisor && b >= pisor){
 if(a %pisor == 0 && b% pisor ==0){
  greatestpisor = pisor;  
 }
 pisor++;
 }
 return greatestpisor;
}
greatestCommonpisor(14, 21); // 7
greatestCommonpisor(69, 169); // = 1

Algorithm Paradigm

很抱歉。我也无法解释它。 因为我自己80%的情况下都不能理解它。 我的算法分析教练告诉我这个,又从课堂笔记偷走(我是一个好学生,顺便说一句!)

function greatestCommonpisor(a, b){
 if(b == 0)
  return a;
 else 
  return greatestCommonpisor(b, a%b);
}

注意:用你的大脑来理解它。

去重

Q:你将如何从数组中删除重复的成员?
A: 执行一个循环,并保存一个对象/关联数组。如果我第一次找到一个元素,我会设置它的值为真(这将告诉我元素添加一次)。如果我在对象中找到这个元素,我不会将它插入到返回数组中。

function removeDuplicate(arr){
 var exists ={},
  outArr = [], 
  elm;
 for(var i =0; i<arr.length removeduplicate><p style="text-align: left;"><span style="color: #ff0000"><strong>合并两个排序的数组</strong></span></p>
<p style="text-align: left;">Q: 怎样合并两个已排序数组?<br>A: 我将为每个数组保留一个指针(看代码,并注意这个)。</p>
<pre class="brush:php;toolbar:false">function mergeSortedArray(a, b){
 var merged = [], 
   aElm = a[0],
   bElm = b[0],
   i = 1,
   j = 1;
 if(a.length ==0)
  return b;
 if(b.length ==0)
  return a;
 /* 
 if aElm or bElm exists we will insert to merged array
 (will go inside while loop)
  to insert: aElm exists and bElm doesn't exists
       or both exists and aElm <p style="text-align: left;">不通过临时<a href="http://www.php.cn/wiki/70.html" target="_blank">变量</a>交换两个数的值</p><p style="text-align: left;">Q:如何在不使用临时变量的情况下交换两个数字?</p><pre class="brush:php;toolbar:false">function swapNumb(a, b){
 console.log('before swap: ','a: ', a, 'b: ', b);
 b = b -a;
 a = a+ b;
 b = a-b;
 console.log('after swap: ','a: ', a, 'b: ', b); 
}
swapNumb(2, 3);
//  = before swap: a: 2 b: 3
//  = after swap: a: 3 b: 2

位操作:对不起,我无法向你解释这一点。 Kinjal Dave建议到 logical conjunction理解它。将浪费您30分钟。

function swapNumb(a, b){
 console.log("a: " + a + " and b: " + b);
 a = a ^ b;
 b = a ^ b;
 a = a ^ b;
 console.log("a: " + a + " and b: " + b);
}
swapNumb(2, 3);
// = a: 2 and b: 3
// = a: 3 and b: 2

字符串反向

Q:如何在JavaScript中反转字符串?
A:可以遍历字符串并将字母连接到新字符串。

方法1

function reverse(str){
 var rtnStr = '';
 for(var i = str.length-1; i>=0;i--){
  rtnStr +=str[i];
 }
 return rtnStr;
}
reverse('you are a nice dude');
// = "edud ecin a era uoy"

Q:你知道在现代浏览器中串联效果很好,但在像IE8这样的旧浏览器中会变慢。 还有什么不同的方法,可以扭转一个字符串?

A:当然.我可以使用数组,也可以添加一些检查。如果字符串是NULL或其他字符串,这将失败。让我也做一些类型检查。使用此数组类似于在某些服务器端语言中使用字符串缓冲区。

方法2

function reverse(str){
 var rtnStr = [];
 if(!str || typeof str != 'string' || str.length =0;i--){
  rtnStr.push(str[i]);
 }
 return rtnStr.join('');
}

Q: 运行时间复杂度是多少?
A: O(n);
Q:可以做得更好?
A:我可以遍历索引的一半,它会节省一点点。 (这是没用的,可能不会打动面试官)

方法3

function reverse(str) {
 str = str.split('');
 var len = str.length,
   halfIndex = Math.floor(len / 2) - 1,
   revStr;
 for (var i = 0; i <p style="text-align: left;">Q:这有效,但你可以做递归的方式吗?<br>A:可以。</p><p style="text-align: left;"><strong>方法4</strong></p><pre class="brush:php;toolbar:false">function reverse (str) {
  if (str === "") {
    return "";
  } else {
    return reverse(str.substr(1)) + str.charAt(0);
  }
}

方法5

Q:你可以在方法中使用任何构建,使它更清洁吗?

function reverse(str){
 if(!str || str.length <p style="text-align: left;"><strong>方法6</strong></p><p style="text-align: left;">Q:你可以做反向函数作为字符串扩展吗?<br>A:我需要将这个函数添加到String.prototype,而不是使用str作为参数,我需要使用this</p><pre class="brush:php;toolbar:false">String.prototype.reverse = function (){
 if(!this || this.length <p style="text-align: left;"><span style="color: #ff0000"><strong>单词反转</strong></span></p><p style="text-align: left;">Q:你如何在句子中颠倒单词?<br>A:您必须检查整个字符串的空白区域。确定是否可能有多个空格。</p><pre class="brush:php;toolbar:false">//have a tailing white space
//fix this later
//now i m sleepy
function reverseWords(str){
 var rev = [], 
   wordLen = 0;
 for(var i = str.length-1; i>=0; i--){
  if(str[i]==' ' || i==0){
   rev.push(str.substr(i,wordLen+1));
   wordLen = 0;
  }
  else
   wordLen++;
 }
 return rev.join(' ');
}

内置方法的快速解决方案:

function reverseWords(str){
 return str.split(' ').reverse();
}

原位反转

Q: 如果你有一个字符串如”I am the good boy”, 怎样变为 “I ma eht doog yob”? 注意这些单词位置不变但是被反转了。

A: 要做到这一点,我必须做字符串反向和字反转。

function reverseInPlace(str){
 return str.split(' ').reverse().join(' ').split('').reverse().join('');
}
reverseInPlace('I am the good boy');// = "I ma eht doog yob"

Q: ok。好的,你能不使用内置反向函数做到吗?
A: (内心独白)有没有搞错!!

//sum two methods.
//you can simply split words by ' '
//and for each words, call reverse function
//put reverse in a separate function
//if u cant do this, 
//have a glass of water, and sleep

第一个非重复字符

Q: 怎么在字符串中找到第一个非重复字符?
A: 有什么条件吗?
A: 比如是否区分大小写?
面试官可能会说No。
A: 是长字符串还是短字符串?
Q: 这些有什么关系吗?

A:例如,如果它是一个非常长的字符串,说一百万个字符,我想检查是否有26个英文字符正在重复。 我可能会检查是否所有字符都在每200个字母中重复(例如),而不是循环遍历整个字符串。 这将节省计算时间。
Q: 简单起见, 这个字符串是 “the quick brown fox jumps then quickly blow air”。

function firstNonRepeatChar(str){
 var len = str.length,
   char, 
   charCount = {};
 for(var i =0; i<len firstnonrepeatchar><p style="text-align: left;">这有一个问题,不能再循环中及时退出。</p>
<p style="text-align: left;"><span style="color: #ff0000"><strong>删除重复的字符</strong></span></p>
<p style="text-align: left;">Q: 怎样删除字符串中的重复字符?</p>
<p style="text-align: left;">A: 这与第一个非重复字符非常相似。你应该问一些类似的问题。它是区分大小写的吗?。</p>
<p style="text-align: left;">如果面试官说,这是区分大小写的,那么你就很轻松了。 如果他说不。你可以使用string.toLowercase()来把字符串。面试官可能不喜欢这个方法。 因为返回字符串不会拥有相同的大小写。 所以</p>
<pre class="brush:php;toolbar:false">function removeDuplicateChar(str){
 var len = str.length,
   char, 
   charCount = {}, 
   newStr = [];
 for(var i =0; i<len removeduplicatechar><p style="text-align: left;"><span style="color: #ff0000"><strong>回文检查</strong></span></p>
<p style="text-align: left;">Q: 如何检查一个字符串是否是回文?</p>
<p style="text-align: left;">A: 把字符串反转,如果反转前后相等,那么它就是回文。</p>
<pre class="brush:php;toolbar:false">function isPalindrome(str){
 var i, len = str.length;
 for(i =0; i<len ispalindrome><p style="text-align: left;">或者</p>
<pre class="brush:php;toolbar:false">function checkPalindrom(str) {
  return str == str.split('').reverse().join('');
}

类似的:在 O(n)时间复杂度内判断一个字符串是否包含在回文字符串内。你能在O(1)时间解决问题吗?

找缺失的数字

Q: 在一个1到100的未排序数组中找到缺失的数,你怎么做?

说明:数组中的数字为1到100。 数组中只有一个数字缺失。数组未排序。找到缺少的数字。

A: 你必须表现得像是在想很多。然后讨论n=n(n+1)/2的线性级数之和

function missingNumber(arr){
 var n = arr.length+1, 
   sum = 0,
   expectedSum = n * (n+1)/2;
 for(var i = 0, len = arr.length; i <p style="text-align: left;">注意: 这个会返回任意长度数组中缺失的那个</p><p style="text-align: left;"><span style="color: #ff0000"><strong>两数之和</strong></span></p><p style="text-align: left;">Q: 在一个未排序的数组中找出是否有任意两数之和等于给定的数?<br>A: 简单!双重循环。</p><pre class="brush:php;toolbar:false">function sumFinder(arr, sum){
 var len = arr.length;
 for(var i =0; i<len-1 sumfinder><p style="text-align: left;">Q: 时间复杂度?<br>A: O(n2)。<br>Q: 有更优解?<br>A: 我想想。我可以用一个对象来存储当前元素和和值的差值。当我拿到一个新元素,如果这个元素的差值在对象中存在,那么我就能判断出是否存在。</p>
<pre class="brush:php;toolbar:false">function sumFinder(arr, sum){
 var differ = {}, 
   len = arr.length,
   substract;
 for(var i =0; i<len sumfinder><p style="text-align: left;"><span style="color: #ff0000"><strong>最大和</strong></span></p>
<p style="text-align: left;">Q: 找到任意两个元素的最大总和?</p>
<p style="text-align: left;">A: 这实际上非常简单直接。 找到两个最大的数字并返回它们的总和</p>
<pre class="brush:php;toolbar:false">function topSum(arr){
 var biggest = arr[0], 
   second = arr[1], 
   len = arr.length, 
   i = 2;
 if (len biggest){
   second = biggest;
   biggest = arr[i];
  }
  else if (arr[i]>second){
   second = arr[i];
  }
 }
 return biggest + second;
}

统计零

Q: 统计从1到n的零总数?

A: 如果 n = 100,则0的数目将是11(0,10,20,30,40,50,60,70,80,90,100)。 请注意,100有两个0.这个看起来很简单,但有点棘手

说明:所以这里的重点是。 如果你有一个1到50的数字,那么这个数值就是5,就是50除以10.然而,如果这个数值是100,这个数值是11,你将得到100/10 = 10和 10/10 = 1。 那就是你将如何在一个数字中得到更多的零,如(100,200,1000);

function countZero(n){
 var count = 0;
 while(n>0){
  count += Math.floor(n/10);
  n = n/10;
 }
 return count;
}
countZero(2014);
// = 223

子字符串

Q: 在字符串中匹配子字符串?

A: 在迭代字符串时将使用指针(一个用于字符串,另一个用于子字符串)。 然后用另一个变量来保存初始匹配的起始索引。

function subStringFinder(str, subStr){
 var idx = 0,
   i = 0,
   j = 0,
   len = str.length,
   subLen = subStr.length;
  for(; i<len substringfinder><p style="text-align: left;"><span style="color: #ff0000"><strong>排列</strong></span></p>
<p style="text-align: left;">Q: 如何获取字符串中的所有排列?</p>
<p style="text-align: left;">A: 根据您对算法的了解程度,这可能会很困难。、</p>
<pre class="brush:php;toolbar:false">function permutations(str){
  var arr = str.split(''),
    len = arr.length, 
    perms = [],
    rest,
    picked,
    restPerms,
    next;
  if (len == 0)
    return [str];
  for (var i=0; i<len><p>相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!</p>
<blockquote><p>相关学习推荐:<a href="https://www.php.cn/course/list/17/type/2.html" target="_blank">javascript视频教程</a></p></blockquote></len>

The above is the detailed content of Algorithms that are easy to encounter in JS interviews. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft