Intro: I am a former accountant turned software engineer graduated from coding bootcamp in January 2022. Algorithms and Data Structure is an unavoidable part of interviews for most of the tech companies now. And one of my friends told me that you need to solve a medium leetcode problem under 60 seconds in order to get into the top tech companies.So I thought I'd start learning how to do it while job searching.
Since I have no clue on how to solve any of the problems (even the easy ones), I thought there is no point for me to waste hours and can't get it figured out. Here is my approach:
- Pick a leetcode problem randomly or Online Assessment from targeted companies.
- Study 1-2 solutions from Youtube or LeetCode discussion section. One brute force solution, another one more optimal.
- Write a blog post with detailed explanation and do a verbal walk through to help understand the solutions better.
- Code out the solution in LeetCode without looking at the solutions
- Combat the forgetting curve: Re-do the question for the next three days. And come back regularly to revisit the problem.
This is my first Linked List problem
83. Remove Duplicates from Sorted List
Difficulty: Easy
Language: JavaScript
Given the head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Input: head = [1,1,2]
Output: [1,2]
Input: head = [1,1,2,3,3]
Output: [1,2,3]
Constraints:
- The number of nodes in the list is in the range
[0, 300]
. -100 <= Node.val <= 100
- The list is guaranteed to be sorted in ascending order.
Solution:
var deleteDuplicates = function(head) {
let current = head;
//let current node equal to head and keep track of current node
while(current !== null && current.next !== null){
//while (note 1) current node and the next node exist, loop will
//start and find the node that is not duplicated. If any of the
//two condition (note 4) is null, the loop will break.
if(current.val === current.next.val){
//if current value of the node equal (note 2) to the next node
current.next = current.next.next
//skip over the next node to the node after that and starts next
//loop
} else {
current = current.next
//if not, move current to the next node and starts next loop
}
}
return head
//return the head will return the entire linked list.
};
Solution Submission detail as of 3/1/2022
(Data below could vary since there are new tests/submissions daily)
- Runtime: 91 ms
- Memory Usage: 41.9 mb
References:
LeetCode Problem Link
Youtube: Terrible Whiteboard
LeetCode Discussion: rickp
Note 1: while statement
Note 2: strictly equal (===)
Note 3: if...else
Note 4: Logical AND (&&)
Blog Cover Image Credit
Top comments (0)