How to solve Leetcode No. 1492: kth Factor of N in JavaScript

Problem Statement

Let’s Explain

factors: 1, 2, 3, 4, 6, 12

Coding up a solution

function kthFactor(n, k) {
let factors = [];
}
function kthFactor(n, k) {
let factors = [];
for (let i = 1; i <= n; i++) {
if (n % i === 0) factors.push(i);
}

}
function kthFactor(n, k) {
let factors = [];
for (let i = 1; i <= n; i++) {
if (n % i === 0) factors.push(i);
if (factors.length === k) return factors[k - 1];
}
return -1;
}

Code Walk Through

  • We begin looping at i = 1
  • Does 12 / 1 have a remainder? Nope, so we push 1 into our factors array.
  • Now our factors array is [1], which is of length 1. Since 1 is not 3, we skip the next conditional and increment i to 2.
  • Does 12 / 2 have a remainder? Also no. So we push 2 into our factors array.
  • Now our factors array is [1, 2], which is of length 2. Since 2 is not 3, we skip the next conditional and increment i to 3.
  • Does 12 / 3 have a remainder? Also no. So we. push 3 into our factors array.
  • Now our factors array is [1, 2, 3], which is of length 3. And now 3 = 3, so our next condition evaluates to true. So we return the number in our factors array at k — 1 (remember to account for the whole arrays starting at 0 index, but we started looping at i = 1 in order to return the nth element of a list), which is factors[2] => 3.

--

--

--

Always learning.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Exploring NestJS — Nest’s module system

Customising Slate js — Part 1 (adding Material UI)

Wordpress letsmakeparty3 redirect hack fix

Learning ReactJS while brushing up my Javascript knowledge (& fighting with command line & other…

Component lifecycles in React functional components with useEffect

20 String Methods in Javascript

Zeronode — minimal building block for NodeJS microservices

Is There an API To Get Precious Metals Rates In Pound Sterling With JSON Format?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Saul Feliz

Saul Feliz

Always learning.

More from Medium

Leetcode: Two Sum (JS)

Byte size info: Stack data Structures

LeetCode #994: Rotting Oranges Problem

How to sort an array of object values based on string?