• How to Practice LeetCode Problems (The Right Way)

Woman working at home

tl;dr: You’re doing it wrong. Use “The Six Steps” any time you practice LeetCode questions, preferably with another person. Keep an interview prep journal to track your progress.

The struggle is real

Have you been tackling LeetCode problems but don’t feel like you’re actually getting better in interviews? Feel like you’re able to come up with solutions but never make it to the optimal one? Do you keep running out of time before you can finish the question? Are you constantly having a tough time making it through difficult questions?

As a former Google software engineer and now career and interview coach, many of my clients have had this problem over the years. And if you were my client, I’d tell you that the problem isn’t that you’re not smart enough. Nor is it that you’re not working hard enough.

You’re probably practicing wrong.

Maybe you’ve been  working through the Blind 75 . Or maybe you’re just using example problems from Cracking the Coding Interview . You can pull questions from wherever you want, I don’t care. If you’re using the wrong strategy, it’s not gonna help you very much, no matter how many questions you practice.

Anyone who’s done weightlifting in the gym knows that good form and flexibility are essential. Those elements are necessary for getting the most out of your workout. Similarly, you need to practice good problem solving techniques when you’re doing LeetCode questions so that you’re maximizing the time you spend.

Keeping the real interview in mind

Many of you practice LeetCode problems incorrectly because you may be unfamiliar with how technical interviews work in real life. Let’s break that down real quick.

More than anything else, you need to understand that technical interviewing is a collaborative problem-solving exercise . The real interview won’t be you working through a LeetCode question by yourself. You’re going to be talking to a real human being. That’s important to state because, if you’re practicing by yourself, you probably aren’t thinking about the fact that you need to communicate out loud to another person and ask questions.

The biggest weakness with LeetCode problems is that there’s no human involved outside of yourself. The question needs to provide every detail necessary for you to solve the problem up front. In a real interview, your interviewer is probably going to hold back some information to see how you deal with ambiguity. In other words, they want to know if you’re going to ask questions or not.

Also, a LeetCode question can’t give you hints if you’re headed in the wrong direction. It can’t give you feedback on whether your approach is sound or not. All of this matters because your interviewer is going to assess how you handle feedback. If I, as your interviewer, ask you about whether you can optimize your solution, I’m going to expect something better than “I don’t know.”

Oh, and by the way, your interviewer isn’t obligated to provide you with examples or test cases. Some may do it to be helpful, and that’s great. But if you’re used to having all of that provided for you in your LeetCode questions, then you’re going to have a hard time in the real interview coming up with good examples and test cases.

A better way

With the necessary context established, let’s talk about how I think you should properly study example questions. The following strategy is what I used to ensure I got the most mileage out of every interview question. These steps will show how I applied my own problem solving framework (I call them “The Six Steps” ) to practice interview questions.

1) Grab something to code on (not an IDE)

Before you begin, make sure that you are set up correctly for your mock interview. You may choose to write out code using a whiteboard, pencil and paper, or using a computer and a text editor or lightweight code editor like Notepad++ or TextPad. Try to avoid using a full-on IDE since they will often include features that you’re not likely to get in a real coding interview.

If you’re working with a mock interviewer, make sure to choose something that they’ll also be able to see and edit.

2) Decide whether to practice with a mock interviewer (strongly recommended) or by yourself

The best way to practice a LeetCode question is with another person who will assess you as an interviewer. Now this is going to come as a shock, but they don’t necessarily need to be a coder! Having a fellow software engineer or developer is ideal of course, but the important thing is finding someone that you can talk to and that can give you feedback. When studying for the Google interview, I relied on my wife who is definitely not technical but provided great feedback on my presence and demeanor.

Of course, there will be times when you will need to study alone and that’s fine. It will be essential for you to keep yourself accountable by not giving yourself more than a mock interviewer would in a real interview.

Oh, and whoever you work with, show them some thanks and appreciation. There’s always something you can do to compensate them for their time, whether with money, coffee, a public acknowledgement, or a gift card.

3) Start the clock

Most interviews are timed for 45-60 minutes. Decide what length of time you’re going to spend doing your mock interview based upon what you can expect for the real thing. Remember, you want to keep things as realistic as possible. Once your time is up, stop working. It’s important to train yourself to work well within time constraints.

One caveat here is that if you’re early into your interview prep journey, you may want to just benchmark yourself a few times to see how well you perform. You’ll still want to time yourself, but don’t stop by a specific time. Keep going until you reach an optimal solution or can’t think of anything else to do.

4) Articulate the problem

Your mock interviewer will begin by reading the question out loud. Under no circumstances during the whole interview are you to look at the sample question, examples, or constraints. Depend completely on your mock interviewer for any information you will need to solve the problem. This is why it is absolutely essential that you take notes as your interviewer is speaking so that you don’t have to ask them repeatedly for information they’ve already revealed.

To ensure you’ve heard the question correctly and that you’ve captured all the details, repeat the question back to your interviewer in your own words. If you’ve missed any details or added something unnecessary, your mock interviewer should let you know before proceeding.

If you’re practicing on your own, read the question out loud exactly one time along with the example. Once done, hide the question from view and then repeat the question in your own words as though you were actually talking to a real person. Take notes, but avoid writing the full problem statement out. Focus on short statements that help you remember the key parts of the problem you’re solving.

5) Ask questions and confirm assumptions

Here’s a handy tip for any interview. Always ask questions as the interviewee. Even if you think you know everything about how to solve a problem, and even if you’ve solved it before—still ask questions. Here are some questions you can ask for nearly any technical question:

  • What’s the data type of the input and range of valid data?
  • Does the input fit in memory?
  • Can I expect to receive invalid data?
  • How will input data be provided?
  • Is the input data sorted already?

Remember, you should avoid asking questions that already have answers in the problem statement itself. It is important and encouraged, however, to re-state your assumptions in the hearing of your interviewer based on your understanding of the problem. For instance, if the problem mentions sorting whole numbers, you might assume that you’re going to be sorting 32-bit signed integers. State that assumption clearly or ask if that’s the case. The problem might actually require you to sort values that fit in a short integer, thus allowing you to save space (or a long 64-bit integer, which would obviously require more).

If you’re practicing alone or if  you’re working with someone non-technical, you won’t have someone to answer your questions. Once you’ve documented all your questions and assumptions, you can peek at the LeetCode constraints at this point and write down the answers.

Again, try not to do a lot of writing. Prefer the least number of words needed to capture the essentials so you don’t have to keep details in your head.

6) Come up with example inputs and their outputs

At this point, you should begin working through examples. Two things are important at this step. One, look through any examples provided for you and reverse engineer them to figure out what details they reveal about the problem or its constraints. Two, add a couple of your own examples to demonstrate your understanding of those constraints or to prompt more questions. A way to think of examples is to treat them like test cases. Read up on test driven development (TDD) and unit testing as part of your interview prep if you habitually struggle to come up with good test cases.

A note to the mock interviewer. If the interviewee comes up with an example that violates constraints, let them know immediately. You are obligated to inform or remind them of the constraints in this case since this information may be critical to their being able to solve the problem.

Again, if you’re studying alone then you won’t have someone who can give you feedback on your examples. That’s OK. Still come up with examples and make best-guess assumptions to any unanswered questions you may generate at this step. LeetCode questions are generally specific enough that this shouldn’t be hard to do.

7) Brainstorm solutions and estimate their Big-O

You should now have enough information to start coming up with solutions to the problem. This is where the rubber meets the road. All of your studying of algorithms and data structures should amply prepare you for generating two or three viable ways to solve the problem. If you struggle a lot at this step, hit the books. You’ve got more learning to do.

The first step to good brainstorming is making a good guess about what the optimal solution looks like as expressed in Big-O. Is it possible that a constant time and constant space solution could exist? Why not? How about a logarithmic solution that ‘s O(lg n)? Remember, you’re always driving towards an optimal solution.

As an example, if I need to sort an array, I’m pretty sure that I can’t do any better than a O(n) time complexity and O(1) space complexity in the worst case. I claim linear time complexity because I’ll probably have to look at every element of input at least once, and I claim constant space because some sorts move elements in place so that I don’t need to use a separate data structure.

Once you think you know the ideal, the next step to good brainstorming is coming up with solutions and predicting their time and space complexity. Note that your first solution is probably going to be a brute force approach that is less than ideal. It also might also be the only solution you can come up with quickly. That’s OK! If that’s all you are able to come up with after a couple of minutes, just move on and go with it. But take the time to try to think about what you can do to get closer to the ideal, optimal solution.

A couple of principles can be helpful here:

  • You usually have to use more space (memory) to make something go faster (and vice-versa), so if you’re optimizing for speed, you probably need to use a data structure.
  • If your task is to build a new data structure, you are likely going to need to put two data structures together that complement each other. That means that in your studying, you should strive to know the strengths and weaknesses of each data structure and what problems they are designed to solve.

Again, take only short notes of your approach along with the expected time and space complexity. Do the estimation up front, even if you aren’t exactly sure! This can help you navigate your way through potential optimizations before you write the first line of code. You might find that a more optimal solution is just as easy, if not easier, to implement than the initial one you devised.

One last thing. You’re going to have to choose a solution to start implementing in the next step. It is OK for you to get input from your interviewer about which one they’d prefer to see you implement. It’s also fine for you to implement the easiest one first and then write an optimal version after that. Hopefully, you can find a great mock interviewer who will provide you with good guidance here.

8) Implement a solution

Now comes the easiest part of the experience. If you don’t find this to be the easiest, then you need to spend more time practicing writing out code. There’s a practical reason why I say this. You want to spend the least amount of time in this step so that you can devote more time to the others. It’s like the old proverb says: “measure twice, cut once.”

Because you are on an artificially constrained, time-boxed schedule, you should also avoid writing in pseudocode. In real life interviews, pseudocode generally doesn’t count. That means you’ll have to turn all your fake code into real code for it to be assessed properly. Instead of pseudocoding, I suggest you make small notes about your proposed algorithm instead of writing out fake code since that will probably be faster and provide the same utility.

Again, we’re talking about coding interviews primarily used by the big tech companies. If you can pseudocode on a take home assignment and make the deadline, go for it! But at the big tech level, I assure you that writing code will be the easiest part of the job. Understanding the work you need to do and vetting your design will probably be the bulk of what makes your job challenging.

  • Say what you’re going to do before you write the code, then write the code. Don’t write code without explaining what you’re writing first. This ensures that the interviewer knows what you are thinking and has the opportunity to interrupt you if you’re going down the wrong path.
  • Use good, clear variable names. Prefer to be verbose (e.g. indexCount instead of idxCnt). In a real interview, your interviewer won’t be the only one looking at your code. Readability matters a lot and is one of the reasons why code reviews are practiced in any major software shop.
  • Don’t be afraid to use common APIs, syntactic sugar, and common idiomatic style for your language. If you have doubts, just ask your interviewer whether you can use something or not. And even more importantly, understand what is happening under the covers so that you’re aware of any performance penalty. For instance, calling the sort method on your collection costs between O(n lg n) or O(n2) depending on your language. Just calling that method won’t magically turn your code into a constant time solution.
  • As part of your practice regimen , writing algorithms from memory can help you both get stronger in your programming language while also strengthening your comprehension of the algorithm itself

Remember, I strongly advise against using an IDE for coding up your solution to practice problems. And if you decide to use the LeetCode editor, don’t compile and run the tests. In most cases, you’re not actually going to get that in a real interview and even if you do, you will be tempted to use it as a crutch instead of properly walking through your code and testing it. Use a real compiler and unit tests after your time is up!

If you find yourself getting stuck during the implementation, use an example and work out the steps on paper to get from input to output. Try to visualize what you need to do on paper so that you can see what your code needs to do and then implement it.

9) Test your code

After you’ve typed the last semicolon or curly brace, you are still not done. You probably have at least one bug, typo, or missing variable that you need to fix. Walk through your code line by line, and check that each line is doing what you designed it to do. You should have a mental checklist of a few things to watch out for:

  • Undeclared variables
  • Off-by-one errors
  • Reversed conditionals (e.g. “<” instead of “>=”)
  • Bad variable names
  • Null pointer exceptions

This is one of the big reasons why it’s essential to work out examples early in the problem solving process. You can easily use one of those examples to mentally run through the code and test that things work well, using paper and pencil or the text editor to track variable state.

10) Optimize

If you haven’t reached an optimal solution yet, either go back to brainstorming or implement a more optimal solution you’ve already devised. Until the timer hits zero, you’ve still got more work to do. Keep going!

Wrapping up your mock interview

Regardless of whether you practice with a partner or on your own, make sure to document feedback on your performance. Keeping a journal or notebook with all your learnings is a very useful way of organizing tips, resources, and your own progress. I still have my mock interview journal that reflects just some of the work I poured into being successful.

If you worked with a mock interviewer, there are two questions you should answer: 1) how do you feel about your own performance, and 2) how would your interviewer rate you between hire, no hire, or on the fence. The key to these two questions is figuring out whether your self-assignment aligns with that of your interviewer. This will help you to shape the right expectations as you prepare so that you can build confidence and gain a good sense for yourself about whether you’re headed in the right direction.

Allow your interviewer space to critique you on non-technical things as well. Did you stumble a lot in your speech or use non-sequiturs? Were you making any annoying noises that should be avoided? Did you go quiet for long stretches of the interview? This feedback might not help you code better, but it will help you to communicate better and that’s half the challenge of doing well on technical interviews.

Lastly, now that your interview is over, feel free to copy your code into the LeetCode tool and make sure that it compiles and that the tests pass. If they don’t take note of any edge cases you missed. I’d actually recommend copying into an IDE so that you can get more detail about compilation errors or use a debugger to step through your code. Take note of failures or missed edge cases so that you can add them to your implementation checklist on the next coding question you tackle.

Want to succeed technical interviews and winning six-figure offers? Register for my free live webinar at morganlatimer.com/webinar . Learn the strategies I’ve used to help my clients land FAANG offers and beyond.

Recent Posts

  • Tired of Educating Your Peers on Race? Think again 
  • gRPC vs REST: Comparing API Styles in Practice
  • How to Transition into Tech: A Complete Guide
  • 9 Things You Didn’t Know About Your Coding Interviewer

DEV Community

DEV Community

Braeden Smith

Posted on Sep 18, 2020 • Updated on Sep 23, 2020

Why JavaScript is actually a great LeetCode/Interview language

In reality, the best language is the one you're comfortable with..

But if you're debating learning a non-strictly typed language, or stuck between several choices, I want to present a couple of reasons why JS might be worth a try.

Everyone is on the LeetCode grind these days.

If you're unfamiliar with LeetCode, it's a way to practice interview-type coding challenges in a short time frame. This article applies to actual interview services too, whether that's HackerRank, CodeSignal, HireVue, or any of the other numerous testing services.

For beginners, it's often parroted that Python, Java and C++ are the "big 3" to learn for LeetCode.

It's often said that C++/Java are great choices because they're super fast, have wide standard libraries, and strictly typed. C++ has a bit more convolution with memory management and iterators, but trades that for speed. Java is notoriously verbose, which is often against the spirit of fast iteration during interviews.

On the other hand, people often like Python since it's similar to writing pseudocode, it has a super beginner friendly community, and is fast to iterate upon.

I'm going to present some reasons (in no particular order) why JavaScript might be the best of both worlds for coding challenges (but especially as an alternative to Python).

I'm going to avoid dissing other languages in my reasoning, because I'm not quite as familiar and wouldn't want to misspeak about features.

#1) - Everything is objects (and that's awesome)

Objects are awesome, flexible, and arguably the most important data association in software development.

I'd argue that "HashMap" type data structures are more valuable and more widely used than arrays. Fun fact: In JS typeof([1]) // 'object' -- even arrays are objects, just with some special additional properties.

But essentially we can use them as replacements to Sets/Maps/Dictionaries in other languages (which I'm sure a crazy high percentage of LeetCode-type problems require). And for problems that need to maintain insertion order we can use Map() and Set() in JS.

We can also easily use objects to represent Linked Lists, Trees, Graphs, Tries and more! This is essential when problems require to build out more complex algorithms.

#2) Sometimes strict, static typing is awesome (but not for speed)

For real maintainable, testable, reliable code, it's almost always to have some typing assistance, whether that's a bit lighter (TypeScript) or super heavy (Rust).

But oftentimes that comes with the trade-off of fast iteration (or writing nothing but auto ).

Learning how type coercion and non-static typing works in JS and similar scripting languages (Python, Ruby) makes it super easy to do fast tricks.

Essentially our JS engine does a best-effort type coercion when we're comparing or operating different types (eg. Number, String, Object, Array) -- that can give us some initially strange side effects. But let's show an example of how we can use this to our advantage!

I use this code basically all the time -- but there's plenty of other instances where this type coersion (especially knowing 0, '', null, undefined are all fasly values).

Reason #3) JSON = JavaScript Object Notation (and the web <3s it)

This advantage applies less to LeetCode problems, but more to take-home assessments. Build a small app to hit and API and do some data manipulation and POST it back to another endpoint.

This is what JS was built for, manipulating and handling data between web services. Almost every API or take-home assessment will involve JSON in some way or another -- and the built-in methods like JSON.stringify() and JSON.parse() make it a breeze.

From personal experience, I've done assessments with HubSpot and many others -- their whole focus is on real-world work for their assessment -- nothing is more real-world then GET requests and parsing JSON.

I was able to work extremely fast through the problems because I don't have to think twice about setting up libraries or schemas -- I just use Axios/Node-fetch and get back a fully usable object that I can manipulate to my heart's content.

And even for testing, being able to just paste JSON into an IDE and it immediately being a valid object to work with is extremely valuable.

#4) Built in array methods make life easy

Array questions are just about the most common input data structure, so you'll be manipulating and iterating through them often.

I'll just quickly enumerate some awesome array methods that I find myself using all the time in LeetCode and interviews (interviewers are often impressed by how quick and easy it makes certain problems).

Basic data manipulation (we can reduce mental complexity and use arrays as stacks and queues in JS)

4) unshift()

Some iterative array manipulation (by order of most useful)

1) forEach()

3) reduce()

5) filter()

1) Turning strings into arrays and vice-versa (super common)

2) reverse()

Read about every array method here

#5) JavaScript execution ( V8 ) is ridiculously quick

Language specific time-outs are supposed to be adjusted to fit the execution model. But I've heard on the internet and from friends, sometimes you'll hit the optimal solution in HackerRank, but still get TLE (time limit exceeded) timeouts for larger test cases in Python.

Worry no longer about execution on larger datasets -- you'll be competing speed-wise with C++ and Java when you use JavaScript (where the V8 JavaScript engine reigns supreme (Chrome, Node.js)).

Essentially if you're able to get an optimal solution, or even something close to it, you'll get through all hidden test cases from a timing perspective.

JS vs Python JS vs C++ JS vs Java

Misc advantages:

These don't necessarily fit neatly in a category, but I felt it was important to bring up these positives.

1) Object destructuring const { result } = { result: "answer" } 2) Optional chaining animal?.color?.hexcode 3) NPM /Yarn -- package.json and large access to libraries for take-home assessments, make package managment a breeze 4) Spread operator Math.max(...a)

A few downfalls or dislikes:

1) Lack of heap structure (at least built-in) 2) Direct string manipulation feels hacky: charAt(), split(), splice() 3) Array slicing feels less clean than Python implementations.

Thanks for reading! Let me know if you have any thoughts, why JS is great or not-great for coding interviews/LeetCode!

Top comments (2)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

kamrulsh profile image

  • Joined Jan 17, 2021

Good article. I use javascript all the time at leetcode. 🚀

manoharreddyporeddy profile image

Heap DS is there. I have asked them last year We can use github.com/datastructures-js/prior... See FAQ page - support.leetcode.com/hc/en-us/arti...

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

adya_kalhari profile image

Free Node.js Hosting: A Quick Guide

Adya Kalhari - Aug 6

hitesh_chauhan_42485a44af profile image

What's New in React 19 : 20 Exciting Features

Hitesh Chauhan - Aug 6

mattlewandowski93 profile image

15 Advanced TypeScript Tips and Tricks You Might Not Know 🤔💡

Matt Lewandowski - Aug 18

kada profile image

React Context API: A Comprehensive Guide

Kada Guetouache - Aug 18

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Get the Reddit app

Discuss interview prep strategies and leetcode questions

leetcode problem solving using javascript

Hi everyone ,

i am solving one leetcode question problem on daily basis using javascript and also making video of it and uploading to youtube

it is to make sure i am consistent with problem solving daily

here is the link to playlist :- https://www.youtube.com/playlist?list=PLJPcOX7rpsL4oNGY7GwdjM_V3sAn3E7YH

please share some feedback if possible

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

JavaScript LeetCode

Mastering Leetcode Problem-Solving Using Simple JavaScript.

JavaScript LeetCode

Bog's tech

Javascript arrays 101 tips and tricks ft. leetcode, learn how to handle arrays in javascript.

Bogdan N.'s photo

13 min read

JavaScript Arrays 101 tips and tricks ft. LeetCode

Table of contents

What is leetcode, max consecutive ones, find numbers with even number of digits, squares of a sorted array, duplicate zeros, merge sorted array, remove element, remove duplicates from sorted array, check if n and its double exist, valid mountain array, replace elements with greatest element on right side, sort array by parity, height checker, third maximum number, find all numbers disappeared in an array.

LeetCode defines itself as

LeetCode is the best platform to help you enhance your skills, expand your knowledge and prepare for technical interviews.

Is it truly the best? That's debatable (I will explain in another article) however it's very useful and it's been a standard for interviews - especially from FAANG companies (or MAANG now) - since the tech boom and the need to filter candidates. I personally like it because I generally enjoy challenging programming problems but most people use the platform just to prepare for interviews.

JavaScript Arrays

image.png

Next you will find all the problems and its solutions with comments. The full repository is here. And you can find me on Twitter @tekbog

Given a binary array nums, return the maximum number of consecutive 1's in the array.

image.png

Given an array nums of integers, return how many of them contain an even number of digits.

image.png

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

image.png

Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.

Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.

image.png

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

image.png

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

image.png

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

image.png

Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).

image.png

Given an array of integers arr, return true if and only if it is a valid mountain array.

image.png

Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.

After doing so, return the array.

image.png

### Move Zeroes Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

image.png

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

Return any array that satisfies this condition.

image.png

A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line.

You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed).

Return the number of indices where heights[i] != expected[i].

image.png

Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.

image.png

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

image.png

javascript problem solving leetcode

Leetcode | Solution of Palindrome Number in JavaScript

In this post, we will solve the palindrome number problem from leetcode using a couple of methods and compare their time and space complexities. Let's begin.

Problem Statement

The question can be found at leetcode palindrome number problem .

The problem states that we need to determine if a given integer is a palindrome.

Constraints and challenges

  • We need to take the sign of number into account while solving the problem. -2 is not a palindrome as 2- is not equal to -2 .

We will discuss three solutions in this article and compare their time & space complexities.

String-based reversal

Number based reversal, two pointer method.

In this method, we will convert the number to a string, reverse it and check if the initial number is equal to the new one. We will use some built-in JavaScript methods.

The idea is very simple

  • convert to string
  • create a character array
  • join it back to a string
  • check for equality

Let's see a simple implementation of the above logic.

Notice the == as opposed to === because we want to check if both sides are equal regardless of their type. In this case, X is a number while the computed value is a string.

Some of the methods chained are

  • toString() to convert the number to a string
  • split() to convert the string to an array of characters
  • reverse() to reverse the array
  • join() to join the array back to a string

This will also solve the problem with the sign of the number. When we convert the number to a string, the minus sign becomes the part of the string and on reversal goes to end. For example, -123 becomes 321- .

This is all we need to solve the problem, once we submit it, these are the stats.

Time and space complexity

Time complexity.

We use a bunch of methods, all with linear time complexity, but they are chained as opposed to nested, so the runtime will be dependent on the number of digits in the input. We can say O(len X)

Space complexity

We have a number as input, not using any other temporary variable to store the result, so space complexity is constant, O(1)

In this method, we will pick the digits of the number one by one and reverse the number without converting it to string

  • check if the number is less than zero
  • if the number is less than zero, return false
  • initialize a variable temp with X ( because we lose the initial value of X in the logic)
  • initialize the reverse variable with 0
  • loop over the number until it's less than or equal to zero (at one point it will be)
  • now, multiply the reversed variable with 10 and add the last digit of the number to it
  • remove the last digit of X
  • when the loop ends, we will have our reversed number
  • if the reversed number is equal to temp ( initial number ), return true
  • else, false

So as discussed above, first we determine if the number is negative, and return false.

You can read more about number based reversal method in my previous post .

Next, the logic is pretty straight forward, check if the reversed number is equal to temp, and return the result.

Here are the stats one we run this code

Time and Space complexity

Unfortunately, we didn't improve the time complexity. It's O(len X) ( notice the loop runs len X times). Same goes for space, O(1) .

In this solution, we will take care of some of the simple cases before writing out logic. Once those are taken care of, we will follow the two-pointer method to check if the number is a palindrome.

The idea is, we will take one digit from the start, and another from the last. Check if both are equal if not, the number is not a palindrome.

First, we took care of the following cases

  • if X is negative ( not a palindrome )
  • if X is less than ten ( always a palindrome )
  • if X has 0 at its last digit and X is not 0 itself ( not a palindrome ) e.g. 10, 130 whose reverse will be 01, 031 respectively

Next, the logic is straight forward

  • convert the number to a string
  • take two pointers, at the start and end of the string
  • if the digits at both pointers are different, it's not a palindrome
  • we increment starting pointer and decrement the end pointer iteratively
  • if the loop exits, then it was a palindrome

We have a number as input, using a couple of more temporary variables, so space complexity is constant, O(1)

So, we solved the palindrome number problem using 3 methods, although the complexity is the same, it's good to know these different approaches. In an interview, you may be asked to solve using two pinter method, who knows.

I hope you enjoyed solving this question. This is it for this one, complete source code for this post can be found on my Github Repo . Will see you in the next one.

There you go guys, you made it to end of the post. Subscribe to my youtube channel for regular updates. Follow me on twitter , drop me a mail or leave a comment here if you still have any doubts and I will try my best to help you out. Thanks

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Solve LeetCode Problems in JavaScript. JavaScript solutions for LeetCode

jyxia/LeetCode-JavaScript

Folders and files.

NameName
98 Commits

Repository files navigation

Leetcode solutions in javascript.

  • Tried to use optimal solutions as much as I can. Most solutions are from the LeetCode community.
  • Written in Airbnb JavaScript style.
  • A work in progress.
  • If you find something wrong or the complexity is not good, you are very welcome to contribute your better solutions.
  • 7. Reverse Integer - Solution
  • 8. String to Integer (atoi) - Solution
  • 9. Palindrome Number - Solution
  • 13. Roman to Integer - Solution
  • 14. Longest Common Prefix - Solution
  • 19. Remove Nth Node From End of List - Solution
  • 20. Valid Parentheses - Solution
  • 21. Merge Two Sorted Lists - Solution
  • 24. Swap Nodes in Pairs - Solution
  • 28. Implement strStr() - Solution
  • 26. Remove Duplicates from Sorted Array - Solution
  • 27. Remove Element - Solution
  • 36. Valid Sudoku - Solution
  • 38. Count and Say - Solution
  • 53. Maximum Subarray - Solution
  • 66. Plus One - Solution
  • 67. Add Binary - Solution
  • 70. Climbing Stairs - Solution
  • 83. Remove Duplicates from Sorted List - Solution
  • 88. Merge Sorted Array - Solution
  • 100. Same Tree - Solution
  • 101. Symmetric Tree - Solution
  • 102. Binary Tree Level Order Traversal - Solution
  • 104. Maximum Depth of Binary Tree - Solution
  • 107. Binary Tree Level Order Traversal II - Solution
  • 110. Balanced Binary Tree - Solution
  • 111. Minimum Depth of Binary Tree - Solution
  • 112. Path Sum - Solution
  • 118. Pascal's Triangle - Solution
  • 119. Pascal's Triangle II - Solution
  • 125. Valid Palindrome - Solution
  • 160. Intersection of Two Linked Lists - Solution
  • 165. Compare Version Numbers - Solution
  • 167. Two Sum II - Input array is sorted - Solution
  • 169. Majority Element - Solution
  • 172. Factorial Trailing Zeroes - Solution
  • 190. Reverse Bits - Solution
  • 191. Number of 1 Bits - Solution
  • 198. House Robber - Solution
  • 202. Happy Number - Solution
  • 203. Remove Linked List Elements - Solution
  • 204. Count Primes - Solution
  • 205. Isomorphic Strings - Solution
  • 206. Reverse Linked List - Solution
  • 217. Contains Duplicate - Solution
  • 219. Contains Duplicate II - Solution
  • 223. Rectangle Area - Solution
  • 225. Implement Stack using Queues - Solution
  • 226. Invert Binary Tree - Solution
  • 228. Summary Ranges - Solution
  • 231. Power of Two - Solution
  • 232. Implement Queue using Stacks - Solution
  • 234. Palindrome Linked List - Solution
  • 235. Lowest Common Ancestor of a Binary Search Tree - Solution
  • 237. Delete Node in a Linked List - Solution
  • 242. Valid Anagram - Solution
  • 243. Shortest Word Distance - Solution
  • 258. Add Digits - Solution
  • 263. Ugly Number - Solution
  • 278. First Bad Version - Solution
  • 283. Move Zeroes - Solution
  • 290. Word Pattern - Solution
  • 299. Bulls and Cows - Solution
  • 303. Range Sum Query - Immutable - Solution
  • 326. Power of Three - Solution
  • 328. Odd Even Linked List - Solution
  • 342. Power of Four - Solution
  • 344. Reverse String - Solution
  • 349. Intersection of Two Arrays - Solution
  • 350. Intersection of Two Arrays II - Solution
  • 367. Valid Perfect Square - Solution
  • 412. Fizz Buzz - Solution
  • 1. Two Sum - Solution
  • 2. Add Two Numbers - Solution
  • 3. Longest Substring Without Repeating Characters - Solution
  • 5. Longest Palindromic Substring - Solution
  • 11. Container With Most Water - Solution
  • 12. Integer to Roman - Solution
  • 15. 3Sum - Solution
  • 16. 3Sum Closest - Solution
  • 17. Letter Combinations of a Phone Number - Solution
  • 22. Generate Parentheses - Solution
  • 29. Divide Two Integers - Solution
  • 31. Next Permutation - Solution
  • 33. Search in Rotated Sorted Array - Solution
  • 34. Search for a Range - Solution
  • 39. Combination Sum - Solution
  • 40. Combination Sum II - Solution
  • 43. Multiply Strings - Solution
  • 46. Permutations - Solution
  • 47. Permutations II - Solution
  • 48. Rotate Image - Solution
  • 49. Group Anagrams - Solution
  • 50. Pow(x, n) - Solution
  • 54. Spiral Matrix - Solution
  • 55. Jump Game - Solution
  • 59. Spiral Matrix II - Solution
  • 60. Permutation Sequence - Solution
  • 61. Rotate List - Solution
  • 62. Unique Paths - Solution
  • 63. Unique Paths II - Solution
  • 64. Minimum Path Sum - Solution
  • 69. Sqrt(x) - Solution
  • 71. Simplify Path - Solution
  • 73. Set Matrix Zeroes - Solution
  • 74. Search a 2D Matrix - Solution
  • 75. Sort Colors - Solution
  • 77. Combinations - Solution
  • 78. Subsets - Solution
  • 79. Word Search - Solution
  • 80. Remove Duplicates from Sorted Array II - Solution
  • 81. Search in Rotated Sorted Array II - Solution
  • 82. Remove Duplicates from Sorted List II - Solution
  • 86. Partition List - Solution
  • 89. Gray Code - Solution
  • 90. Subsets II - Solution
  • 91. Decode Ways - Solution
  • 92. Reverse Linked List II - Solution
  • 93. Restore IP Addresses - Solution
  • 94. Binary Tree Inorder Traversal - Solution
  • 96. Unique Binary Search Trees - Solution
  • 98. Validate Binary Search Tree - Solution
  • 103. Binary Tree Zigzag Level Order Traversal - Solution
  • 105. Construct Binary Tree from Preorder and Inorder Traversal - Solution
  • 106. Construct Binary Tree from Inorder and Postorder Traversal - Solution
  • 108. Convert Sorted Array to Binary Search Tree - Solution
  • 109. Convert Sorted List to Binary Search Tree - Solution
  • 113. Path Sum II - Solution
  • 114. Flatten Binary Tree to Linked List - Solution
  • 116. Populating Next Right Pointers in Each Node - Solution
  • 120. Triangle - Solution
  • 121. Best Time to Buy and Sell Stock - Solution
  • 122. Best Time to Buy and Sell Stock II - Solution
  • 129. Sum Root to Leaf Numbers - Solution
  • 127. Word Ladder - Solution
  • 130. Surrounded Regions - Solution
  • 131. Palindrome Partitioning - Solution
  • 134. Gas Station - Solution
  • 136. Single Number - Solution
  • 139. Word Break - Solution
  • 141. Linked List Cycle - Solution
  • 142. Linked List Cycle II - Solution
  • 143. Reorder List - Solution
  • 144. Binary Tree Preorder Traversal - Solution
  • 147. Insertion Sort List - Solution
  • 148. Sort List - Solution
  • 150. Evaluate Reverse Polish Notation - Solution
  • 151. Reverse Words in a String - Solution
  • 152. Maximum Product Subarray - Solution
  • 153. Find Minimum in Rotated Sorted Array - Solution
  • 162. Find Peak Element - Solution
  • 173. Binary Search Tree Iterator - Solution
  • 179. Largest Number - Solution
  • 199. Binary Tree Right Side View - Solution
  • 213. House Robber II - Solution
  • 215. Kth Largest Element in an Array - Solution
  • 216. Combination Sum III - Solution
  • 221. Maximal Square - Solution
  • 227. Basic Calculator II - Solution
  • 229. Majority Element II - Solution
  • 230. Kth Smallest Element in a BST - Solution
  • 236. Lowest Common Ancestor of a Binary Tree - Solution
  • 238. Product of Array Except Self - Solution
  • 240. Search a 2D Matrix II - Solution
  • 241. Different Ways to Add Parentheses - Solution
  • 244. Shortest Word Distance II - Solution
  • 245. Shortest Word Distance III - Solution
  • 260. Single Number III - Solution
  • 268. Missing Number - Solution
  • 274. H-Index - Solution
  • 284. Peeking Iterator - Solution
  • 300. Longest Increasing Subsequence - Solution
  • 309. Best Time to Buy and Sell Stock with Cooldown - Solution
  • 318. Maximum Product of Word Lengths - Solution
  • 319. Bulb Switcher - Solution
  • 331. Verify Preorder Serialization of a Binary Tree - Solution
  • 337. House Robber III - Solution
  • 338. Counting Bits - Solution
  • 347. Top K Frequent Elements - Solution
  • 515. Find Largest Value in Each Tree Row - Solution
  • 23. Merge k Sorted Lists - Solution
  • 25. Reverse Nodes in k-Group - Solution
  • 32. Longest Valid Parentheses - Solution
  • 41. First Missing Positive - Solution
  • 45. Jump Game II - Solution
  • 56. Merge Intervals - Solution
  • 57. Insert Interval - Solution
  • 65. Valid Number - Solution
  • 115. Distinct Subsequences - Solution
  • 117. Populating Next Right Pointers in Each Node II - Solution
  • 123. Best Time to Buy and Sell Stock III - Solution
  • 132. Palindrome Partitioning II - Solution
  • 145. Binary Tree Postorder Traversal - Solution
  • 154. Find Minimum in Rotated Sorted Array II - Solution
  • 273. Integer to English Words - Solution
  • 287. Find the Duplicate Number - Solution
  • JavaScript 99.4%

IMAGES

  1. Daily JavaScript Problem Solving

    javascript problem solving leetcode

  2. leetcode-javascript-solutions · GitHub Topics · GitHub

    javascript problem solving leetcode

  3. Solving "Search Insert Position" from LeetCode ( Easy )

    javascript problem solving leetcode

  4. LeetCode Problem Javascript Solution

    javascript problem solving leetcode

  5. Solving LeetCode 153 in JavaScript (Find Minimum in Rotated Sorted

    javascript problem solving leetcode

  6. Solving LeetCode 66 in JavaScript (Plus One)

    javascript problem solving leetcode

COMMENTS

  1. Problems

    Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

  2. 30 Days of JavaScript

    Complete the study plan to win the badge! Related. View More

  3. bhartik021/LeetCode-30-Days-of-JavaScript

    Welcome to the LeetCode 30 Days JavaScript Solution Repository! In this repository, you will find JavaScript solutions to the LeetCode 30-Day Challenge problems. This collection of solutions is designed to help you enhance your problem-solving skills, improve your algorithmic thinking, and become a better programmer. Resources

  4. LeetCode Problem 2623 Memoize

    A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value. You can assume there are 3 possible input functions: sum, fib, and ...

  5. Key JavaScript Concepts I Mastered During LeetCode's 30-Day ...

    Recently, they announced a 30-day JavaScript coding challenge, which was entirely focused on solving problems using JavaScript concepts and constructs. The best part was their in-depth editorial ...

  6. 2000+ javascript solutions of leetcode problems.

    2000+ javascript solutions of leetcode problems. javascript algorithms leetcode solutions data-structures problems 1000plus 1100plus 1200plus 1300plus 1400plus 1500plus 1600plus 1700plus 1800plus 1900plus 2000plus 2100plus 2200plus. Activity.

  7. Two Sum Problem: JS Solutions Guide

    Discover solutions for the Two Sum Problem in JavaScript. This guide offers detailed, step-by-step explanations and complexity analysis for optimal learning. ... LeetCode Solve: Two Sum.

  8. How to Practice LeetCode Problems (The Right Way)

    Focus on short statements that help you remember the key parts of the problem you're solving. 5) Ask questions and confirm assumptions. Here's a handy tip for any interview. Always ask questions as the interviewee. Even if you think you know everything about how to solve a problem, and even if you've solved it before—still ask questions.

  9. leetcode-javascript-solutions · GitHub Topics · GitHub

    Add this topic to your repo. To associate your repository with the leetcode-javascript-solutions topic, visit your repo's landing page and select "manage topics." GitHub is where people build software. More than 100 million people use GitHub to discover, fork, and contribute to over 420 million projects.

  10. Why JavaScript is actually a great LeetCode/Interview language

    Reason #3) JSON = JavaScript Object Notation (and the web <3s it) This advantage applies less to LeetCode problems, but more to take-home assessments. Build a small app to hit and API and do some data manipulation and POST it back to another endpoint. This is what JS was built for, manipulating and handling data between web services.

  11. Plus One

    Can you solve this real interview question? Plus One - Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. Can you solve this real interview question? Plus One - Level up your coding skills and quickly land a job.

  12. leetcode problem solving using javascript : r/leetcode

    Hi everyone , i am solving one leetcode question problem on daily basis using javascript and also making video of it and uploading to youtube it is…

  13. LeetCode Problem 2627 Debounce

    Solving Leetcode 30 Days of JavaScript study plan problems in JavaScript and TypeScript Problem: Given a function fn and a time in milliseconds t , return a debounced version of that function.

  14. JavaScript Leetcode

    Mastering Leetcode Problem-Solving Using Simple JavaScript.

  15. LitCodeSolver

    Primarily focus on LeetCode questions, but I've got you covered on all problems! What I will do for you: Provide the code to your problem. Explain the code. Provide time complexity. Provide space complexity. An AI that solves and explain your leetcode and other coding problems.

  16. Add Strings

    Can you solve this real interview question? Add Strings - Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. Can you solve this real interview question? Add Strings - Level up your coding skills and quickly land a job.

  17. Repository of LeetCode Solutions using JavaScript.

    Hello 👋, Welcome to my repository of LeetCode Solutions using JavaScript. I often solve LeetCode problems, which helps me to write more optimised and efficient code. It mainly focuses on our intuition to approach towards any problem.

  18. JavaScript Arrays tips and tricks with LeetCode problems

    I personally like it because I generally enjoy challenging programming problems but most people use the platform just to prepare for interviews. JavaScript Arrays. LeetCode has something called "Explore Cards" so I decided to dive into Arrays Next you will find all the problems and its solutions with comments. The full repository is here.

  19. Solving the LeetCode Two Sum Problem with JavaScript

    Approaches to Solve the Problem. The easiest way to solve this problem is by using a brute force approach, which involves two nested loops. For each element in the array, we check whether there ...

  20. Leetcode

    Problem Statement. The question can be found at leetcode palindrome number problem. The problem states that we need to determine if a given integer is a palindrome. Constraints and challenges. We need to take the sign of number into account while solving the problem. -2 is not a palindrome as 2- is not equal to -2. Solutions

  21. GitHub

    Solve LeetCode Problems in JavaScript. JavaScript solutions for LeetCode - jyxia/LeetCode-JavaScript

  22. Two Sum

    Can you solve this real interview question? Two Sum - Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. Can you solve this real interview question? Two Sum - Level up your coding skills and quickly land a job.

  23. Palindrome Number: JavaScript LeetCode Solutions

    If they are equal, the number is a palindrome. Step 1: We convert the integer to a string, allowing us to easily manipulate its characters. Step 2: We reverse the string by splitting it into an ...