Data Structures In JavaScript
Leetcode Problems
Data Structures In JavaScript
Problem:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Solution:
Mind the last carry.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Array": https://leetcode.com/tag/array "Binary Search": https://leetcode.com/tag/binary-search "Divide and Conquer": https://leetcode.com/tag/divide-and-conquer
Problem:
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
Example 2:
Solution:
O(log (m+n)) means half of the sequence is ruled out on each loop. So obviously we need binary search.
To do it on two sorted arrays, we need a formula to guide division.
Let nums3
be the sorted array combining all the items in nums1
and nums2
.
If nums2[j-1] <= nums1[i] <= nums2[j]
, then we know nums1[i]
is at num3[i+j]
. Same goes nums1[i-1] <= nums2[j] <= nums1[i]
.
Let k
be ⌊(m+n-1)/2⌋
. We need to find nums3[k]
(and also nums3[k+1]
if m+n is even).
Let i + j = k
, if we find nums2[j-1] <= nums1[i] <= nums2[j]
or nums1[i-1] <= nums2[j] <= nums1[i]
, then we got k
.
Otherwise, if nums1[i] <= nums2[j]
then we know nums1[i] < nums2[j-1]
(because we did not find k
).
There are
i
items beforenums1[i]
, andj-1
items brefornums2[j-1]
, which meansnums1[0...i]
are beforenums3[i+j-1]
. So we now knownums1[0...i] < nums3[k]
. They can be safely discarded.We Also have
nums1[i] < nums2[j]
, which meansnums2[j...n)
are afternums3[i+j]
. Sonums2[j...n) > nums3[k]
.
Same goes nums1[i-1] <= nums2[j] <= nums1[i]
.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "String": https://leetcode.com/tag/string
Problem:
The string "PAYPALISHIRING"
is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
Example 1:
Example 2:
Solution:
Squeeze the zigzag pattern horizontally to form a matrix. Now deal with the odd and even columns respectively.
For example let numRows be 5, if we list out the indecies:
First calculate the matrix width:
We can easily make a observation that the direction of odd and even columns and different.
Let the first column be index 0 and let i be the current position at column col.
We need to count the items between matrix[row][col] and matrix[row][col+1], exclusive.
If row == 1 or row == numRows, skip the odd columns.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Math": https://leetcode.com/tag/math Similar Questions: "String to Integer (atoi)": https://leetcode.com/problems/string-to-integer-atoi
Problem:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Example 2:
Example 3:
Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution:
ONE
This is a JavaScript specific solution. It is esay to write but slow to run because it generates O(n) space. This could end up a huge array.
TWO
Pure mathamatical solution.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Math": https://leetcode.com/tag/math "String": https://leetcode.com/tag/string Similar Questions: "Reverse Integer": https://leetcode.com/problems/reverse-integer "Valid Number": https://leetcode.com/problems/valid-number
Problem:
Implement atoi
which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:
Only the space character ' '
is considered as whitespace character.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Solution:
ONE
TWO
Looks like Number()
is faster than parseInt()
.
THREE
General solution.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Math": https://leetcode.com/tag/math Similar Questions: "Palindrome Linked List": https://leetcode.com/problems/palindrome-linked-list
Problem:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Example 2:
Example 3:
Follow up:
Coud you solve it without converting the integer to a string?
Solution:
ONE
Easy to write but slow since it generates an array.
TWO
A bit faster.
THREE
General solution. Combining 7. Reverse Integer.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "String": https://leetcode.com/tag/string "Dynamic Programming": https://leetcode.com/tag/dynamic-programming "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "Wildcard Matching": https://leetcode.com/problems/wildcard-matching
Problem:
Given an input string (s
) and a pattern (p
), implement regular expression matching with support for '.'
and '*'
.
The matching should cover the entire input string (not partial).
Note:
s
could be empty and contains only lowercase letters a-z
.
p
could be empty and contains only lowercase letters a-z
, and characters like .
or *
.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Solution:
ONE
Cheating with real RegExp matching.
TWO
Let f(i, j) be the matching result of s[0...i) and p[0...j).
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Two Pointers": https://leetcode.com/tag/two-pointers Similar Questions: "Trapping Rain Water": https://leetcode.com/problems/trapping-rain-water
Problem:
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
Solution:
Greedy Algorithm.
If we look at the simple brute force approach, where we choose one point at a time and calculate all the possible areas with other points on the right, it is easy to make a observation that we are narrowing down the horizontal distance.
Greedy Algorithm can help us skip some of the conditions. It is base on a fact that the area between two columns are determined by the shorter one.
Let's say we have pointer l
and r
at the begin and end of a distance, and the area is area(l, r)
, how should we narrow down the distance?
If height[l] < height[r]
, we know that the height of the area will never be greater than height[l]
if we keep l
. Now if we get rid of r
, the area can only get smaller since the distance is shorter, and the height is at most height[l]
.
Here we conclude rule NO.1: Get rid of the smaller one.
What if height[l] == height[r]
? It is safe to get rid of both. We do not need any of them to constrain the max height of the rest points.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Math": https://leetcode.com/tag/math "String": https://leetcode.com/tag/string Similar Questions: "Roman to Integer": https://leetcode.com/problems/roman-to-integer "Integer to English Words": https://leetcode.com/problems/integer-to-english-words
Problem:
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
For example, two is written as II
in Roman numeral, just two one's added together. Twelve is written as, XII
, which is simply X
+ II
. The number twenty seven is written as XXVII
, which is XX
+ V
+ II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Solution:
Treat 4, 40, 400 and 9, 90, 900 specially.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Math": https://leetcode.com/tag/math "String": https://leetcode.com/tag/string Similar Questions: "Integer to Roman": https://leetcode.com/problems/integer-to-roman
Problem:
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
For example, two is written as II
in Roman numeral, just two one's added together. Twelve is written as, XII
, which is simply X
+ II
. The number twenty seven is written as XXVII
, which is XX
+ V
+ II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Solution:
Normally we just add up the digits, except when the digit is greater than its left (e.g. IV). In that case we need to fallback and remove the last digit then combine the two as new digit. That is why we subtract the last digit twice.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "String": https://leetcode.com/tag/string
Problem:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
Example 2:
Note:
All given inputs are in lowercase letters a-z
.
Solution:
ONE
JavaScript specific solution. Get the min len then narrow down the prefix.
TWO
THREE
General solution. Build up the prefix.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Two Pointers": https://leetcode.com/tag/two-pointers Similar Questions: "Two Sum": https://leetcode.com/problems/two-sum "3Sum Closest": https://leetcode.com/problems/3sum-closest "4Sum": https://leetcode.com/problems/4sum "3Sum Smaller": https://leetcode.com/problems/3sum-smaller
Problem:
Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Solution:
To simplify the problem, sort the nums first.
If sorted[0] > 0
or sorted[last] < 0
, return an empty set.
From i = 0
to len(sorted) - 2
, pick sorted[i]
as the first number of a possible triplet result.
Let l = i + 1
, r = len(sorted) - 1
, we want to narrow them down to enumerate all possible combinations.
l++
ifsorted[i] + sorted[l] + sorted[r] > 0
.r--
ifsorted[i] + sorted[l] + sorted[r] < 0
.
Skip any duplicate number as we iterate to avoid duplicate triplets.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Two Pointers": https://leetcode.com/tag/two-pointers Similar Questions: "3Sum": https://leetcode.com/problems/3sum "3Sum Smaller": https://leetcode.com/problems/3sum-smaller
Problem:
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Solution:
Simplified version of 15. 3Sum.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "String": https://leetcode.com/tag/string "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "Generate Parentheses": https://leetcode.com/problems/generate-parentheses "Combination Sum": https://leetcode.com/problems/combination-sum "Binary Watch": https://leetcode.com/problems/binary-watch
Problem:
Given a string containing digits from 2-9
inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
Solution:
ONE
JavaScript specific optimization.
Array.prototype.push
accepts arbitrary arguments which enables tighter loops.
Also, appending string is faster than prepending.
TWO
General recursive DFS solution.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Hash Table": https://leetcode.com/tag/hash-table "Two Pointers": https://leetcode.com/tag/two-pointers Similar Questions: "Two Sum": https://leetcode.com/problems/two-sum "3Sum": https://leetcode.com/problems/3sum "4Sum II": https://leetcode.com/problems/4sum-ii
Problem:
Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
such that a + b + c + d = target
? Find all unique quadruplets in the array which gives the sum of target
.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Solution:
Like 15. 3Sum and 16. 3Sum Closest. Wrap one more loop.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Linked List": https://leetcode.com/tag/linked-list "Two Pointers": https://leetcode.com/tag/two-pointers
Problem:
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
Solution:
Set a pointer p1
for iterating, and p2
which is n
nodes behind, pointing at the (n+1)-th node from the end of list.
Boundaries that should be awared of:
p2
could be one node beforehead
, which means thehead
should be removed.p2
could be larger than the length of the list (Though the description saysn
will always be valid, we take care of it anyway).It should be
p1.next
touches the end rather thanp1
because we wantp1
pointing at the last node.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "String": https://leetcode.com/tag/string "Stack": https://leetcode.com/tag/stack Similar Questions: "Generate Parentheses": https://leetcode.com/problems/generate-parentheses "Longest Valid Parentheses": https://leetcode.com/problems/longest-valid-parentheses "Remove Invalid Parentheses": https://leetcode.com/problems/remove-invalid-parentheses
Problem:
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Solution:
Stack 101.
Whenever we meet a close bracket, we want to compare it to the last open bracket.
That is why we use stack to store open brackets: first in, last out.
And since there is only bracket characters, the last open bracket happens to be the last character.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Linked List": https://leetcode.com/tag/linked-list Similar Questions: "Merge k Sorted Lists": https://leetcode.com/problems/merge-k-sorted-lists "Merge Sorted Array": https://leetcode.com/problems/merge-sorted-array "Sort List": https://leetcode.com/problems/sort-list "Shortest Word Distance II": https://leetcode.com/problems/shortest-word-distance-ii
Problem:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Solution:
Keep tracking the head of two lists and keep moving the pointer of smaller one to the next node.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "String": https://leetcode.com/tag/string "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "Letter Combinations of a Phone Number": https://leetcode.com/problems/letter-combinations-of-a-phone-number "Valid Parentheses": https://leetcode.com/problems/valid-parentheses
Problem:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
Solution:
ONE
Recursive DFS backtracking.
TWO
BFS.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Linked List": https://leetcode.com/tag/linked-list "Divide and Conquer": https://leetcode.com/tag/divide-and-conquer "Heap": https://leetcode.com/tag/heap Similar Questions: "Merge Two Sorted Lists": https://leetcode.com/problems/merge-two-sorted-lists "Ugly Number II": https://leetcode.com/problems/ugly-number-ii
Problem:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Solution:
ONE
Extend the idea of 21. Merge Two Sorted Lists and compare N items at a time.
This is slow as it reaches O(N^2).
TWO
Priority Queue. O(N * log(K)).
Since JavaScript does not provide a standard built-in Priority Queue data structure, it is challenging to implement an efficient one barehanded.
THREE
Divide and conquer. Also O(N * log(K)).
Divide N lists into ceil(N/2) pairs and merge your way up.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Linked List": https://leetcode.com/tag/linked-list Similar Questions: "Reverse Nodes in k-Group": https://leetcode.com/problems/reverse-nodes-in-k-group
Problem:
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Solution:
Draw the nodes down on paper to reason about the relationships.
Pointing to every active node is an easy way to keep on track.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Linked List": https://leetcode.com/tag/linked-list Similar Questions: "Swap Nodes in Pairs": https://leetcode.com/problems/swap-nodes-in-pairs
Problem:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
Only constant extra memory is allowed.
You may not alter the values in the list's nodes, only nodes itself may be changed.
Solution:
Find the end node of a portion that needs to be reversed.
Get the next node of the end node.
Reverse the portion using the next node as edge(null) pointer.
Connect it back to the main linked list.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Array": https://leetcode.com/tag/array "Two Pointers": https://leetcode.com/tag/two-pointers Similar Questions: "Remove Element": https://leetcode.com/problems/remove-element "Remove Duplicates from Sorted Array II": https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii
Problem:
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Example 2:
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
Solution:
The result array can only be shorter. That is why we can build the array in-place with the new length.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Array": https://leetcode.com/tag/array "Two Pointers": https://leetcode.com/tag/two-pointers Similar Questions: "Remove Duplicates from Sorted Array": https://leetcode.com/problems/remove-duplicates-from-sorted-array "Remove Linked List Elements": https://leetcode.com/problems/remove-linked-list-elements "Move Zeroes": https://leetcode.com/problems/move-zeroes
Problem:
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example 1:
Example 2:
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
Solution:
The order does not matter. So just take the last number to fill the vacancy.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Math": https://leetcode.com/tag/math "Binary Search": https://leetcode.com/tag/binary-search
Problem:
Given two integers dividend
and divisor
, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend
by divisor
.
The integer division should truncate toward zero.
Example 1:
Example 2:
Note:
Both dividend and divisor will be 32-bit signed integers.
The divisor will never be 0.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
Solution:
Every decimal number can be represented as a0*2^0 + a1*2^1 + a2*2^2 + ... + an*2^n
.
Replace multiplication and division with binary shifting.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array Similar Questions: "Permutations": https://leetcode.com/problems/permutations "Permutations II": https://leetcode.com/problems/permutations-ii "Permutation Sequence": https://leetcode.com/problems/permutation-sequence "Palindrome Permutation II": https://leetcode.com/problems/palindrome-permutation-ii
Problem:
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
Solution:
Observe a few longer examples and the pattern is self-evident.
Divide the list into two parts. The first half must be incremental and the second half must be decremental.
Reverse the second half and find the smallest number in it that is greater the last number of the first half.
Swap the two.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Binary Search": https://leetcode.com/tag/binary-search Similar Questions: "Search in Rotated Sorted Array II": https://leetcode.com/problems/search-in-rotated-sorted-array-ii "Find Minimum in Rotated Sorted Array": https://leetcode.com/problems/find-minimum-in-rotated-sorted-array
Problem:
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7]
might become [4,5,6,7,0,1,2]
).
You are given a target value to search. If found in the array return its index, otherwise return -1
.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Example 2:
Solution:
Obviously the problem requires binary search.
The core idea of binary search is to pick the middle item and then decide to keep which half.
The precondition of it is the array must be sorted.
But take a closer look and we realize that only one of the two halves needs to be sorted. This is sufficient for us to know if the target is in that half. If not, then it must be in the other.
Whenever we choose a pivot, it must be in one of the two sorted parts of the rotated array.
If the pivot is in the left part. We know that the begin of the left part to the pivot are sorted.
Otherwise the pivot is in the right part. We know that the end of the right part to the pivot are sorted.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Binary Search": https://leetcode.com/tag/binary-search Similar Questions: "First Bad Version": https://leetcode.com/problems/first-bad-version
Problem:
Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
Example 1:
Example 2:
Solution:
Implement two variations of binary search to get the first and last matching positions.
They are basically the same as simple binary search except when we got the match, we mark the index and keep moving forward.
If we want to get the first, we dump the right half. Vice versa.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Array": https://leetcode.com/tag/array "Binary Search": https://leetcode.com/tag/binary-search Similar Questions: "First Bad Version": https://leetcode.com/problems/first-bad-version
Problem:
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Example 2:
Example 3:
Example 4:
Solution:
Same as simple binary search except it returns the start index when does not find a match.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Hash Table": https://leetcode.com/tag/hash-table Similar Questions: "Sudoku Solver": https://leetcode.com/problems/sudoku-solver
Problem:
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits
1-9
without repetition.Each column must contain the digits
1-9
without repetition.Each of the 9
3x3
sub-boxes of the grid must contain the digits1-9
without repetition.
A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
Example 1:
Example 2:
Note:
A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.
The given board contain only digits
1-9
and the character'.'
.The given board size is always
9x9
.
Solution:
Scan the board once.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Hash Table": https://leetcode.com/tag/hash-table "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "Valid Sudoku": https://leetcode.com/problems/valid-sudoku
Problem:
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Each of the digits
1-9
must occur exactly once in each row.Each of the digits
1-9
must occur exactly once in each column.Each of the the digits
1-9
must occur exactly once in each of the 93x3
sub-boxes of the grid.
Empty cells are indicated by the character '.'
.
Note:
The given board contain only digits
1-9
and the character'.'
.You may assume that the given Sudoku puzzle will have a single unique solution.
The given board size is always
9x9
.
Solution:
DFS + backtracking.
Just like 36. Valid Sudoku but instead of validating the board with three tables, we use these three tables to get all the valid numbers at a position. This is super fast as it skips a lot of redundant comparisons.
Every time we reach a position, we pick a possible solution and move on to the next position, which is an identical problem.
If the next position fails, we come back and try the next possible solution of the current position.
If all possible solutions fail, we just dump the current position and go back to the last position.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "String": https://leetcode.com/tag/string Similar Questions: "Encode and Decode Strings": https://leetcode.com/problems/encode-and-decode-strings "String Compression": https://leetcode.com/problems/string-compression
Problem:
The count-and-say sequence is the sequence of integers with the first five terms as following:
1
is read off as "one 1"
or 11
.
11
is read off as "two 1s"
or 21
.
21
is read off as "one 2
, then one 1"
or 1211
.
Given an integer n, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Example 2:
Solution:
Just loop and grow the sequence.
ONE
JavaScript specific.
TWO
General solution.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "Letter Combinations of a Phone Number": https://leetcode.com/problems/letter-combinations-of-a-phone-number "Combination Sum II": https://leetcode.com/problems/combination-sum-ii "Combinations": https://leetcode.com/problems/combinations "Combination Sum III": https://leetcode.com/problems/combination-sum-iii "Factor Combinations": https://leetcode.com/problems/factor-combinations "Combination Sum IV": https://leetcode.com/problems/combination-sum-iv
Problem:
Given a set of candidate numbers (candidates
) (without duplicates) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
The same repeated number may be chosen from candidates
unlimited number of times.
Note:
All numbers (including
target
) will be positive integers.The solution set must not contain duplicate combinations.
Example 1:
Example 2:
Solution:
DFS + Backtracking.
To prevent duplications, only loop the right side of the candidates.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "Combination Sum": https://leetcode.com/problems/combination-sum
Problem:
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
All numbers (including
target
) will be positive integers.The solution set must not contain duplicate combinations.
Example 1:
Example 2:
Solution:
Mostly the same as 39. Combination Sum.
Now the candidates might have duplicate numbers, so we need to sort it.
We can also safely return when number is larger than the target.
To prvent duplicate results, stop searching if the current number is same as the last.
Notice the number at start
is immune by the rule because we assume that the current group of candidates begins at start
.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Array": https://leetcode.com/tag/array Similar Questions: "Missing Number": https://leetcode.com/problems/missing-number "Find the Duplicate Number": https://leetcode.com/problems/find-the-duplicate-number "Find All Numbers Disappeared in an Array": https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array "Couples Holding Hands": https://leetcode.com/problems/couples-holding-hands
Problem:
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Example 2:
Example 3:
Note:
Your algorithm should run in O(n) time and uses constant extra space.
Solution:
The last requirement is why this problem is marked "hard". Though the solution feels like cheating: it modifies the array to mark numbers.
So the algorithm still requires O(n) space but O(1) extra space.
The core idea of the solution is, if the length of the array is n, then the smallest missing positive integer must be within [1, n+1].
Consider an edge-case scenario where the array is [1,2,...,n]
. The smallest missing positive integer is n+1
.
Now if one of these integers is missing in the array, that integer is the smallest missing positive integer.
If more than one are missing, pick the smallest.
So here we reuse the array and keep trying to put integer k
into the slot indexed k-1
(via swapping).
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Array": https://leetcode.com/tag/array "Two Pointers": https://leetcode.com/tag/two-pointers "Stack": https://leetcode.com/tag/stack Similar Questions: "Container With Most Water": https://leetcode.com/problems/CONTENT-with-most-water "Product of Array Except Self": https://leetcode.com/problems/product-of-array-except-self "Trapping Rain Water II": https://leetcode.com/problems/trapping-rain-water-ii "Pour Water": https://leetcode.com/problems/pour-water
Problem:
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
Example:
Solution:
Well explained by Leetcode official: https://leetcode.com/articles/trapping-rain-water/ .
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Math": https://leetcode.com/tag/math "String": https://leetcode.com/tag/string Similar Questions: "Add Two Numbers": https://leetcode.com/problems/add-two-numbers "Plus One": https://leetcode.com/problems/plus-one "Add Binary": https://leetcode.com/problems/add-binary "Add Strings": https://leetcode.com/problems/add-strings
Problem:
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Example 1:
Example 2:
Note:
The length of both
num1
andnum2
is < 110.Both
num1
andnum2
contain only digits0-9
.Both
num1
andnum2
do not contain any leading zero, except the number 0 itself.You must not use any built-in BigInteger library or convert the inputs to integer directly.
Solution:
Same as we do multiplication on a paper.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Array": https://leetcode.com/tag/array "Greedy": https://leetcode.com/tag/greedy Similar Questions: "Jump Game": https://leetcode.com/problems/jump-game
Problem:
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Note:
You can assume that you can always reach the last index.
Solution:
Greedy. Always pick the one that would allow to jump to the rightest.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "Next Permutation": https://leetcode.com/problems/next-permutation "Permutations II": https://leetcode.com/problems/permutations-ii "Permutation Sequence": https://leetcode.com/problems/permutation-sequence "Combinations": https://leetcode.com/problems/combinations
Problem:
Given a collection of distinct integers, return all possible permutations.
Example:
Solution:
One position at a time, pick a number from the unused set and put it in that position (by swapping). Then move on to the next.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "Next Permutation": https://leetcode.com/problems/next-permutation "Permutations": https://leetcode.com/problems/permutations "Palindrome Permutation II": https://leetcode.com/problems/palindrome-permutation-ii
Problem:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Solution:
Same as 46. Permutations. To avoid duplication, when picking a number for a position, only pick the unused. Either sort the nums
or use a set to mark.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array
Problem:
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Example 2:
Solution:
Outside-in. Rotate one square at a time.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Hash Table": https://leetcode.com/tag/hash-table "String": https://leetcode.com/tag/string Similar Questions: "Valid Anagram": https://leetcode.com/problems/valid-anagram "Group Shifted Strings": https://leetcode.com/problems/group-shifted-strings
Problem:
Given an array of strings, group anagrams together.
Example:
Note:
All inputs will be in lowercase.
The order of your output does not matter.
Solution:
It's all about hashing the words.
ONE
Sort each word to get the key.
TWO
Use the product of prime numbers to generate unique keys.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Math": https://leetcode.com/tag/math "Binary Search": https://leetcode.com/tag/binary-search Similar Questions: "Sqrt(x)": https://leetcode.com/problems/sqrtx "Super Pow": https://leetcode.com/problems/super-pow
Problem:
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Example 2:
Example 3:
Note:
-100.0 < x < 100.0
n is a 32-bit signed integer, within the range [−231, 231 − 1]
Solution:
Corner cases:
n == 0
n < 0
Note here we can not use any bitwise operator, n = -2^31
might overflow.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "N-Queens II": https://leetcode.com/problems/n-queens-ii
Problem:
The n-queens puzzle is the problem of placing n queens on an n_×_n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space respectively.
Example:
Solution:
Allocate a n
-length array queens
. Each item represents a queen coordinate on the borad. Let index i
be the row index, and queens[i]
be the column index (or vice versa).
Now use the permutation algorithm from 46. Permutations to generate all possible queen positions, then test for diagonal.
ONE
This is slow because we test diagonal in the end. We can do a tree pruning by moving it right before diving into the next recursion.
TWO
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "N-Queens": https://leetcode.com/problems/n-queens
Problem:
The n-queens puzzle is the problem of placing n queens on an n_×_n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Solution:
Just modify 51. N-Queens.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Array": https://leetcode.com/tag/array "Divide and Conquer": https://leetcode.com/tag/divide-and-conquer "Dynamic Programming": https://leetcode.com/tag/dynamic-programming Similar Questions: "Best Time to Buy and Sell Stock": https://leetcode.com/problems/best-time-to-buy-and-sell-stock "Maximum Product Subarray": https://leetcode.com/problems/maximum-product-subarray "Degree of an Array": https://leetcode.com/problems/degree-of-an-array
Problem:
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Solution:
DP.
Define f(i)
to be the largest sum of a contiguous subarray that ends with nums[i]
.
If f(i-1)
is negative, then nums[i]
must be greater than f(i-1) + nums[i]
.
Then return the largest one.
We can also compress the dp array:
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array Similar Questions: "Spiral Matrix II": https://leetcode.com/problems/spiral-matrix-ii
Problem:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Example 2:
Solution:
Loop outside-in. Break each cycle into four stages. Note that the last two stages need at least two rows/columns.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Greedy": https://leetcode.com/tag/greedy Similar Questions: "Jump Game II": https://leetcode.com/problems/jump-game-ii
Problem:
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example 1:
Example 2:
Solution:
ONE
See 45. Jump Game II. If the range does not expand at some point, we know it is stuck.
TWO
If we view it backward, and if the range of nums[n-2]
covers nums[n-1]
, then we can safely make n-2
the new destination point, and so on.
If nums[0]
can cover the last destination point, it is good.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Sort": https://leetcode.com/tag/sort Similar Questions: "Insert Interval": https://leetcode.com/problems/insert-interval "Meeting Rooms": https://leetcode.com/problems/meeting-rooms "Meeting Rooms II": https://leetcode.com/problems/meeting-rooms-ii "Teemo Attacking": https://leetcode.com/problems/teemo-attacking "Add Bold Tag in String": https://leetcode.com/problems/add-bold-tag-in-string "Range Module": https://leetcode.com/problems/range-module "Employee Free Time": https://leetcode.com/problems/employee-free-time "Partition Labels": https://leetcode.com/problems/partition-labels
Problem:
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Example 2:
Solution:
Sort then merge.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Array": https://leetcode.com/tag/array "Sort": https://leetcode.com/tag/sort Similar Questions: "Merge Intervals": https://leetcode.com/problems/merge-intervals "Range Module": https://leetcode.com/problems/range-module
Problem:
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Example 2:
Solution:
The logic of the solution is pretty straight forward. Just need to carefully think through all the edge cases. It is better to choose readability over performance.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "String": https://leetcode.com/tag/string
Problem:
Given a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
Example:
Solution:
JavaScript specific solutions:
ONE
TWO
Super fast. split
will guarantee that there is at least one item in the resulted array.
THREE
General solution.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array Similar Questions: "Spiral Matrix": https://leetcode.com/problems/spiral-matrix
Problem:
Given a positive integer n, generate a square matrix filled with elements from 1 to _n_2 in spiral order.
Example:
Solution:
Straight-forward.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Math": https://leetcode.com/tag/math "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "Next Permutation": https://leetcode.com/problems/next-permutation "Permutations": https://leetcode.com/problems/permutations
Problem:
The set [1,2,3,...,*n*]
contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the _k_th permutation sequence.
Note:
Given n will be between 1 and 9 inclusive.
Given k will be between 1 and n! inclusive.
Example 1:
Example 2:
Solution:
The order of the sequence is fixed hence can be calculated. We can view the process as picking digits from a sorted set [1...n]
.
Each digit appears (n-1)!
times in result[0]
. And for a fixed result[0]
each digit appears (n-2)!
times in result[1]
. So on.
We also need k--
to convert k
into index so that k <= (n-1)!
maps 0
(and get 1
from the set).
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Linked List": https://leetcode.com/tag/linked-list "Two Pointers": https://leetcode.com/tag/two-pointers Similar Questions: "Rotate Array": https://leetcode.com/problems/rotate-array "Split Linked List in Parts": https://leetcode.com/problems/split-linked-list-in-parts
Problem:
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Example 2:
Solution:
Classic two-pointers chasing except the k
could be larger than the length of this list.
We first attempt to locate the right pointer while also recording the length of the list.
If we hit the end of list and still do not have the right pointer, we know k
is larger than the length.
Locate the right pointer again with k % len
.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Dynamic Programming": https://leetcode.com/tag/dynamic-programming Similar Questions: "Unique Paths II": https://leetcode.com/problems/unique-paths-ii "Minimum Path Sum": https://leetcode.com/problems/minimum-path-sum "Dungeon Game": https://leetcode.com/problems/dungeon-game
Problem:
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Example 2:
Solution:
DP.
Define f(i, j)
to be the number of total unique paths from (0, 0)
to (i, j)
.
Only two previous states are dependant. Use dynamic array to reduce memory allocation.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Dynamic Programming": https://leetcode.com/tag/dynamic-programming Similar Questions: "Unique Paths": https://leetcode.com/problems/unique-paths "Dungeon Game": https://leetcode.com/problems/dungeon-game "Cherry Pickup": https://leetcode.com/problems/cherry-pickup
Problem:
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example:
Solution:
Define f(i, j)
to be the min sum from (0, 0)
to (i, j)
.
Only two previous states are dependant. Use dynamic array to reduce memory allocation.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Math": https://leetcode.com/tag/math "String": https://leetcode.com/tag/string Similar Questions: "String to Integer (atoi)": https://leetcode.com/problems/string-to-integer-atoi
Problem:
Validate if a given string is numeric.
Some examples:
"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
Solution:
JavaScript specific solutions:
ONE
Math.abs
will first convert the argument to number.Math.abs(' ') === 0
.
TWO
isNaN
will first convert the argument to number.isNaN(' ') === false
.
THREE
General solution. Take a look at the ECMA Spec.
Similary, we can define our own syntax, which requires a few changes:
Now implement the parser. It is much easier now because we have a clear mental map of the syntax.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Array": https://leetcode.com/tag/array "Math": https://leetcode.com/tag/math Similar Questions: "Multiply Strings": https://leetcode.com/problems/multiply-strings "Add Binary": https://leetcode.com/problems/add-binary "Plus One Linked List": https://leetcode.com/problems/plus-one-linked-list
Problem:
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Example 2:
Solution:
ONE
JavaScript specific solution. Note that unshift
is much slower that expanding.
TWO
General solution.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "String": https://leetcode.com/tag/string
Problem:
Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' '
when necessary so that each line has exactly maxWidth characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.
Note:
A word is defined as a character sequence consisting of non-space characters only.
Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
The input array
words
contains at least one word.
Example 1:
Example 2:
Example 3:
Solution:
Count the current line width (plus 1 space between each two words).
When a line is full:
If there is only one word, pad spaces at the end.
Otherwise calculate the gap length using
Math.ceil
.
Handle the last line.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Math": https://leetcode.com/tag/math "Binary Search": https://leetcode.com/tag/binary-search Similar Questions: "Pow(x, n)": https://leetcode.com/problems/powx-n "Valid Perfect Square": https://leetcode.com/problems/valid-perfect-square
Problem:
Implement int sqrt(int x)
.
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Example 2:
Solution:
Binary Search. The square root of x is within [0...(x+1)/2].
Template generated via Leetmark.
Difficulty: Medium Related Topics: "String": https://leetcode.com/tag/string "Stack": https://leetcode.com/tag/stack
Problem:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Corner Cases:
Did you consider the case where path =
"/../"
? In this case, you should return"/"
.Another corner case is the path might contain multiple slashes
'/'
together, such as"/home//foo/"
. In this case, you should ignore redundant slashes and return"/home/foo"
.
Solution:
Use stack to handle /../
.
ONE
RegExp matching.
TWO
Direct search.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "String": https://leetcode.com/tag/string "Dynamic Programming": https://leetcode.com/tag/dynamic-programming Similar Questions: "One Edit Distance": https://leetcode.com/problems/one-edit-distance "Delete Operation for Two Strings": https://leetcode.com/problems/delete-operation-for-two-strings "Minimum ASCII Delete Sum for Two Strings": https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings
Problem:
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Example 2:
Solution:
DP.
Define f(i, j)
to be the min edit distance from word1[0...i)
to word2[0...j)
.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array Similar Questions: "Game of Life": https://leetcode.com/problems/game-of-life
Problem:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Example 2:
Follow up:
A straight forward solution using O(m**n) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
Solution:
O(m**n) space solution: Copy a new matrix.
O(m + n) space solution: Use extra arrays to store rows and columns that need to be set 0.
Constant space solutions:
ONE
Instead of allocating extra arrays. Just use the first row and column.
First scan through the first row and column to see if they need be set 0. If so, mark and do it in the end.
Now scan the matrix and set 0 to the first row and column whenever a 0 is met.
Walk the matrix again and set 0 according to the first row and column.
Finally set the first row and column to 0 if needed.
TWO
Use NaN
to mark cells that need to be set 0.
Still constant space just a bit slower due to repeatedly setting overlapping NaN
s.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Binary Search": https://leetcode.com/tag/binary-search Similar Questions: "Search a 2D Matrix II": https://leetcode.com/problems/search-a-2d-matrix-ii
Problem:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Example 2:
Solution:
ONE
Search from top-left to bottom-right. O(n).
TWO
Binary search. O(log_n_).
View the matrix as an sorted array that is cut into n
slices.
Take the algorithm from 35. Search Insert Position.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Two Pointers": https://leetcode.com/tag/two-pointers "Sort": https://leetcode.com/tag/sort Similar Questions: "Sort List": https://leetcode.com/problems/sort-list "Wiggle Sort": https://leetcode.com/problems/wiggle-sort "Wiggle Sort II": https://leetcode.com/problems/wiggle-sort-ii
Problem:
Given an array with n objects colored red, white or blue, sort them in-placeso that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library's sort function for this problem.
Example:
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with a one-pass algorithm using only constant space?
Solution:
One-pass algorithm.
Take the idea of the partition algorithm from quick sort. Use 1
as pivot.
Count the number of sorted 0
s and 2
s so that we know where to swap.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "Combination Sum": https://leetcode.com/problems/combination-sum "Permutations": https://leetcode.com/problems/permutations
Problem:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Solution:
Basic DFS + Backtracking.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Backtracking": https://leetcode.com/tag/backtracking "Bit Manipulation": https://leetcode.com/tag/bit-manipulation Similar Questions: "Subsets II": https://leetcode.com/problems/subsets-ii "Generalized Abbreviation": https://leetcode.com/problems/generalized-abbreviation "Letter Case Permutation": https://leetcode.com/problems/letter-case-permutation
Problem:
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Solution:
ONE
BFS.
Or more imperative. Loop backward to avoid crossing the boundary.
TWO
DFS + Backtracking.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "Word Search II": https://leetcode.com/problems/word-search-ii
Problem:
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
Solution:
DFS + Backtracking. Replace the cell with NaN
before proceeding to the next level and restore when backtracking.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Two Pointers": https://leetcode.com/tag/two-pointers Similar Questions: "Remove Duplicates from Sorted Array": https://leetcode.com/problems/remove-duplicates-from-sorted-array
Problem:
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Example 2:
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
Solution:
Similar to 26. Remove Duplicates from Sorted Array.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Binary Search": https://leetcode.com/tag/binary-search Similar Questions: "Search in Rotated Sorted Array": https://leetcode.com/problems/search-in-rotated-sorted-array
Problem:
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6]
might become [2,5,6,0,0,1,2]
).
You are given a target value to search. If found in the array return true
, otherwise return false
.
Example 1:
Example 2:
Follow up:
This is a follow up problem to Search in Rotated Sorted Array, where
nums
may contain duplicates.Would this affect the run-time complexity? How and why?
Solution:
See 33. Search in Rotated Sorted Array. The code is basically the same. Except with duplicates we can not tell which way to jump when pivot == nums[e]
. The only thing we can do is to ditch nums[e]
. SO worst case O(*n*)
.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Linked List": https://leetcode.com/tag/linked-list Similar Questions: "Remove Duplicates from Sorted List": https://leetcode.com/problems/remove-duplicates-from-sorted-list
Problem:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Example 2:
Solution:
p1
points to the current node. p
points to the node before p1
so that we can ditch p1
if needed.
The list is sorted so we only need dupVal
to keep the latest duplicate value.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Linked List": https://leetcode.com/tag/linked-list Similar Questions: "Remove Duplicates from Sorted List II": https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii
Problem:
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Example 2:
Solution:
ONE
Just like 82. Remove Duplicates from Sorted List II except keeping the first duplicate node.
TWO
Just compare the next node. This is way more faster.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Array": https://leetcode.com/tag/array "Stack": https://leetcode.com/tag/stack Similar Questions: "Maximal Rectangle": https://leetcode.com/problems/maximal-rectangle
Problem:
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area = 10
unit.
Example:
Solution:
The height of a rectangle is determined by the lowest bar inside of it. So the core idea is, for each bar, assume it is the lowest bar and see how far it can expand. Then we have len(heights)
rectangles. Return the max area.
For a bar b
whose height is h
, find the closest bar b1
on the left that is lower than h
, and b2
on the right. The area of the rectangle is h * (i2 - i1 - 1)
.
Notice that if we just loop the bars from left to right, b1
and b2
of each bar may overlap.
index | height | width | area |
---|---|---|---|
|
|
|
|
0 | 2 | 1 - -1 - 1 | 2 |
1 | 1 | 6 - -1 - 1 | 6 |
2 | 5 | 4 - 1 - 1 | 10 |
3 | 6 | 4 - 2 - 1 | 6 |
4 | 2 | 6 - 1 - 1 | 8 |
5 | 3 | 6 - 4 - 1 | 3 |
Observe how i1
and i2
changes depending on the height.
To reduce O(n^2) to O(n), we use a stack to store incremental b
s. Because b1
and b2
are both lower than b
, whenever we reach a bar that is lower than the top of the stack, we know it's a b2
. So stack top is a b
. Second top is a b1
. Keep popping the b
to calculate areas until b2
is no longer lower than stack top.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Array": https://leetcode.com/tag/array "Hash Table": https://leetcode.com/tag/hash-table "Dynamic Programming": https://leetcode.com/tag/dynamic-programming "Stack": https://leetcode.com/tag/stack Similar Questions: "Largest Rectangle in Histogram": https://leetcode.com/problems/largest-rectangle-in-histogram "Maximal Square": https://leetcode.com/problems/maximal-square
Problem:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Solution:
ONE
View every row as a base line then we just have to solve height(matrix)
times the problem of 84. Largest Rectangle in Histogram.
TWO
Same idea as above. Use DP to cache accumulated states.
Pick a pivot point (row, col)
and assume it is on the base line. The adjoining 1
s above (row, col)
makes up the height of the rectangle. The width of the rectangle is determined by how many ajoining bars are taller than the pivot bar.
So for the rectangle whose bottom pivot is (row, col)
:
Define
area(row, col)
to be the area.Define
height(row, col)
to be the height.Define
left(row, col)
to be thecol
value of the bottom-left corner.Define
right(row, col)
to be thecol
value of the bottom-right corner.
Also:
Define
conLeft(row, col)
to be thecol
value of the leftmost cell of the consecutive1
s on the left of(row, col)
.Define
conRight(row, col)
to be thecol
value of the rightmost cell of the consecutive1
s on the right of(row, col)
.
With conLeft
and conRight
we can know if the rectangle on (row, col)
shrinks comparing to (row-1, col)
.
We only need to keep the last state. Use dynamic arrays to reduce space complexity.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Linked List": https://leetcode.com/tag/linked-list "Two Pointers": https://leetcode.com/tag/two-pointers
Problem:
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Solution:
Take the second part out as a new list and connect it back.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Array": https://leetcode.com/tag/array "Two Pointers": https://leetcode.com/tag/two-pointers Similar Questions: "Merge Two Sorted Lists": https://leetcode.com/problems/merge-two-sorted-lists
Problem:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Solution:
Loop backward and keep picking the larger one. nums1
is guaranteed longer than nums2
so just use n
as boundary.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "1-bit and 2-bit Characters": https://leetcode.com/problems/1-bit-and-2-bit-characters
Problem:
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
Example 1:
Example 2:
Solution:
The pattern is self-evident. Reverse the result set and prepend '1' to each item.
Use bitwise shift to speed up the calculation. It is unlikely to overflow since the result set is exponential.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "Subsets": https://leetcode.com/problems/subsets
Problem:
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Solution:
See 78. Subsets. Except:
Sort input to group duplicates.
Only consider each duplicate once, that is, when it is at the first slot.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "String": https://leetcode.com/tag/string "Dynamic Programming": https://leetcode.com/tag/dynamic-programming Similar Questions: "Decode Ways II": https://leetcode.com/problems/decode-ways-ii
Problem:
A message containing letters from A-Z
is being encoded to numbers using the following mapping:
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Example 2:
Solution:
Define f(i)
to be the number of ways to decode s[0...i]
.
Note that there could be '0'
.
Only need to store the last two states. Init f(-1) = 1
for easy calculation.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Linked List": https://leetcode.com/tag/linked-list Similar Questions: "Reverse Linked List": https://leetcode.com/problems/reverse-linked-list
Problem:
Reverse a linked list from position m to n. Do it in one-pass.
**Note:**1 ≤ m ≤ n ≤ length of list.
Example:
Solution:
Break the list into 3 parts.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "String": https://leetcode.com/tag/string "Backtracking": https://leetcode.com/tag/backtracking Similar Questions: "IP to CIDR": https://leetcode.com/problems/ip-to-cidr
Problem:
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Solution:
Backtracking. Note that leading '0'
is not allowed except just '0'
.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "String": https://leetcode.com/tag/string "Dynamic Programming": https://leetcode.com/tag/dynamic-programming
Problem:
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example 1:
Example 2:
Solution:
Define f(i, j)
to be whether s3[0...i+j-1)
can be formed by the interleaving of s1[0...i)
and s2[0...j)
.
Dynamic array can be used.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search
Problem:
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Example 2:
Example 3:
Solution:
The code should be self-evident.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search "Breadth-first Search": https://leetcode.com/tag/breadth-first-search
Problem:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
But the following [1,2,2,null,3,null,3]
is not:
Note: Bonus points if you could solve it both recursively and iteratively.
Solution:
ONE
The result of pre-order and post-order traversal on a symmetric tree should be the same.
So just like 100. Same Tree. Except one is pre-order traversal and the other is post-order.
TWO
Level order traversal. Check symmetry before entering the next level.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Tree": https://leetcode.com/tag/tree "Breadth-first Search": https://leetcode.com/tag/breadth-first-search Similar Questions: "Binary Tree Zigzag Level Order Traversal": https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal "Binary Tree Level Order Traversal II": https://leetcode.com/problems/binary-tree-level-order-traversal-ii "Minimum Depth of Binary Tree": https://leetcode.com/problems/minimum-depth-of-binary-tree "Binary Tree Vertical Order Traversal": https://leetcode.com/problems/binary-tree-vertical-order-traversal "Average of Levels in Binary Tree": https://leetcode.com/problems/average-of-levels-in-binary-tree "N-ary Tree Level Order Traversal": https://leetcode.com/problems/n-ary-tree-level-order-traversal
Problem:
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
return its level order traversal as:
Solution:
The code should be self-evident.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Stack": https://leetcode.com/tag/stack "Tree": https://leetcode.com/tag/tree "Breadth-first Search": https://leetcode.com/tag/breadth-first-search Similar Questions: "Binary Tree Level Order Traversal": https://leetcode.com/problems/binary-tree-level-order-traversal
Problem:
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
return its zigzag level order traversal as:
Solution:
Reverse the level when pushing to the reuslt.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search Similar Questions: "Balanced Binary Tree": https://leetcode.com/problems/balanced-binary-tree "Minimum Depth of Binary Tree": https://leetcode.com/problems/minimum-depth-of-binary-tree "Maximum Depth of N-ary Tree": https://leetcode.com/problems/maximum-depth-of-n-ary-tree
Problem:
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
return its depth = 3.
Solution:
The code should be self-evident.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search Similar Questions: "Construct Binary Tree from Inorder and Postorder Traversal": https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal
Problem:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
For example, given
Return the following binary tree:
Solution:
Pattern of preorder traversal result: pre(root) = root + pre(root.left) + pre(root.right)
Pattern of inorder traversal result: in(root) = in(root.left) + root + in(root.right)
There are no duplicates so get the first item in preorder result, pinpoint it in inorder result. Then we know the size of left and right subtree.
Repeat the process on subtrees.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search Similar Questions: "Construct Binary Tree from Preorder and Inorder Traversal": https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
Problem:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
For example, given
Return the following binary tree:
Solution:
Pattern of inorder traversal result: in(root) = in(root.left) + root + in(root.right)
Pattern of postorder traversal result: post(root) = post(root.left) + post(root.right) + root
There are no duplicates so get the first item in preorder result, pinpoint it in inorder result. Then we know the size of left and right subtree.
Repeat the process on subtrees.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Tree": https://leetcode.com/tag/tree "Breadth-first Search": https://leetcode.com/tag/breadth-first-search Similar Questions: "Binary Tree Level Order Traversal": https://leetcode.com/problems/binary-tree-level-order-traversal "Average of Levels in Binary Tree": https://leetcode.com/problems/average-of-levels-in-binary-tree
Problem:
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
return its bottom-up level order traversal as:
Solution:
See 102. Binary Tree Level Order Traversal.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search Similar Questions: "Maximum Depth of Binary Tree": https://leetcode.com/problems/maximum-depth-of-binary-tree
Problem:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
Return false.
Solution:
Get the depth of subtrees and compare. Prune the DFS tree by returning -1
.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search "Breadth-first Search": https://leetcode.com/tag/breadth-first-search Similar Questions: "Binary Tree Level Order Traversal": https://leetcode.com/problems/binary-tree-level-order-traversal "Maximum Depth of Binary Tree": https://leetcode.com/problems/maximum-depth-of-binary-tree
Problem:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
return its minimum depth = 2.
Solution:
Ignore null
children.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search Similar Questions: "Path Sum II": https://leetcode.com/problems/path-sum-ii "Binary Tree Maximum Path Sum": https://leetcode.com/problems/binary-tree-maximum-path-sum "Sum Root to Leaf Numbers": https://leetcode.com/problems/sum-root-to-leaf-numbers "Path Sum III": https://leetcode.com/problems/path-sum-iii "Path Sum IV": https://leetcode.com/problems/path-sum-iv
Problem:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
Solution:
Note that node value could be negative so pruning can not be performed.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search Similar Questions: "Path Sum": https://leetcode.com/problems/path-sum "Binary Tree Paths": https://leetcode.com/problems/binary-tree-paths "Path Sum III": https://leetcode.com/problems/path-sum-iii "Path Sum IV": https://leetcode.com/problems/path-sum-iv
Problem:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
Return:
Solution:
Simple backtracking.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search Similar Questions: "Flatten a Multilevel Doubly Linked List": https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list
Problem:
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
The flattened tree should look like:
Solution:
Return the leaf node of a flattened subtree for concatenation.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "String": https://leetcode.com/tag/string "Dynamic Programming": https://leetcode.com/tag/dynamic-programming
Problem:
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE"
is a subsequence of "ABCDE"
while "AEC"
is not).
Example 1:
Example 2:
Solution:
Define f(i, j)
to be the number of ways that generate T[0...j)
from S[0...i)
.
For f(i, j)
you can always skip S[i-1]
, but can only take it when S[i-1] === T[j-1]
.
Dynamic array can be used.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search Similar Questions: "Populating Next Right Pointers in Each Node II": https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii "Binary Tree Right Side View": https://leetcode.com/problems/binary-tree-right-side-view
Problem:
Given a binary tree
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
Note:
You may only use constant extra space.
Recursive approach is fine, implicit stack space does not count as extra space for this problem.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
Example:
Given the following perfect binary tree,
After calling your function, the tree should look like:
Solution:
ONE
Recursive.
For every node
:
Left child: points to
node.right
.Right child: points to
node.next.left
ifnode.next
exists.
TWO
Level order traversal.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search Similar Questions: "Populating Next Right Pointers in Each Node": https://leetcode.com/problems/populating-next-right-pointers-in-each-node
Problem:
Given a binary tree
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
Note:
You may only use constant extra space.
Recursive approach is fine, implicit stack space does not count as extra space for this problem.
Example:
Given the following binary tree,
After calling your function, the tree should look like:
Solution:
ONE
Recursive. See 116. Populating Next Right Pointers in Each Node.
The tree may not be perfect now. So keep finding next
until there is a node with children, or null
.
This also means post-order traversal is required.
TWO
Level order traversal. Exact same as 116. Populating Next Right Pointers in Each Node.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Array": https://leetcode.com/tag/array Similar Questions: "Pascal's Triangle II": https://leetcode.com/problems/pascals-triangle-ii
Problem:
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Solution:
Dynamic Programming 101.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Array": https://leetcode.com/tag/array Similar Questions: "Pascal's Triangle": https://leetcode.com/problems/pascals-triangle
Problem:
Given a non-negative index k where k ≤ 33, return the _k_th index row of the Pascal's triangle.
Note that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
Solution:
Dynamic Programming 101 with dynamic array.
State (i, j)
depends on (i-1, j)
and (i-1, j-1)
. So to access (i-1, j-1)
iteration must be from right to left.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Array": https://leetcode.com/tag/array "Dynamic Programming": https://leetcode.com/tag/dynamic-programming
Problem:
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
The minimum path sum from top to bottom is 11
(i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
Solution:
Define f(i, j)
to be the minimum path sum from triangle[0][0]
to triangle[i][j]
.
Dynamic array can be used.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Array": https://leetcode.com/tag/array "Dynamic Programming": https://leetcode.com/tag/dynamic-programming Similar Questions: "Maximum Subarray": https://leetcode.com/problems/maximum-subarray "Best Time to Buy and Sell Stock II": https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii "Best Time to Buy and Sell Stock III": https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii "Best Time to Buy and Sell Stock IV": https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv "Best Time to Buy and Sell Stock with Cooldown": https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown
Problem:
Say you have an array for which the _i_th element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
Example 2:
Solution:
Only care about positive profits. Take the frist item as base and scan to the right. If we encounter an item j
whose price price[j]
is lower than the base (which means if we sell now the profit would be negative), we sell j-1
instead and make j
the new base.
Because price[j]
is lower that the base, using j
as new base is guaranteed to gain more profit comparing to the old one.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Array": https://leetcode.com/tag/array "Greedy": https://leetcode.com/tag/greedy Similar Questions: "Best Time to Buy and Sell Stock": https://leetcode.com/problems/best-time-to-buy-and-sell-stock "Best Time to Buy and Sell Stock III": https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii "Best Time to Buy and Sell Stock IV": https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv "Best Time to Buy and Sell Stock with Cooldown": https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown "Best Time to Buy and Sell Stock with Transaction Fee": https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
Problem:
Say you have an array for which the _i_th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Example 2:
Example 3:
Solution:
Sell immediately after the price drops. Or in other perspective, it is the sum of all the incremental pairs (buy in then immediately sell out).
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Array": https://leetcode.com/tag/array "Dynamic Programming": https://leetcode.com/tag/dynamic-programming Similar Questions: "Best Time to Buy and Sell Stock": https://leetcode.com/problems/best-time-to-buy-and-sell-stock "Best Time to Buy and Sell Stock II": https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii "Best Time to Buy and Sell Stock IV": https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv "Maximum Sum of 3 Non-Overlapping Subarrays": https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays
Problem:
Say you have an array for which the _i_th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
**Note:**You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Example 2:
Example 3:
Solution:
Multiple transactions may not be engaged in at the same time. That means if we view the days that involed in the same transaction as a group, there won't be any intersection. We may complete at most two transactions, so divide the days into two groups, [0...k]
and [k...n-1]
. Notice k
exists in both groups because technically we can sell out then immediately buy in at the same day.
Define p1(i)
to be the max profit of day [0...i]
. This is just like the problem of 121. Best Time to Buy and Sell Stock.
Define p2(i)
to be the max profit of day [i...n-1]
. This is the mirror of p1
.
Define f(k)
to be p1(k) + p2(k)
. We need to get max( f(0), ..., f(n-1) )
.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search Similar Questions: "Path Sum": https://leetcode.com/problems/path-sum "Sum Root to Leaf Numbers": https://leetcode.com/problems/sum-root-to-leaf-numbers "Path Sum IV": https://leetcode.com/problems/path-sum-iv "Longest Univalue Path": https://leetcode.com/problems/longest-univalue-path
Problem:
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Example 2:
Solution:
For every node
, there are six possible ways to get the max path sum:
With
node.val
node.val
plus the max sum of a path that ends withnode.left
.node.val
plus the max sum of a path that starts withnode.right
.node.val
plus the max sum of both paths.Just
node.val
(the max sum of both paths are negative).
Without
node.val
(disconnected)The max-sum path is somewhere under the
node.left
subtree.The max-sum path is somewhere under the
node.right
subtree.
There are two ways to implement this.
ONE
Define a function that returns two values. The max sum of a path that may or may not end with root
node, and the max sum of the path that ends with root
node.
TWO
Just return the later (max sum of a path that ends with root
). Maintain a global variable to store the disconnected max sum.
Template generated via Leetmark.
Difficulty: Easy Related Topics: "Two Pointers": https://leetcode.com/tag/two-pointers "String": https://leetcode.com/tag/string Similar Questions: "Palindrome Linked List": https://leetcode.com/problems/palindrome-linked-list "Valid Palindrome II": https://leetcode.com/problems/valid-palindrome-ii
Problem:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Example 2:
Solution:
ONE
TWO
Remove non-alphanumeric characters then compare.
THREE
Compare the char codes.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Array": https://leetcode.com/tag/array "String": https://leetcode.com/tag/string "Backtracking": https://leetcode.com/tag/backtracking "Breadth-first Search": https://leetcode.com/tag/breadth-first-search Similar Questions: "Word Ladder": https://leetcode.com/problems/word-ladder
Problem:
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
Example 1:
Example 2:
Solution:
This is just like 127. Word Ladder.
The constrain still works, but instead of deleting the words right away, collect them and delete them all when a level ends, so that we can reuse the words (matching different parents in the same level).
The items in the queue are not just words now. Parent nodes are also kept so that we can backtrack the path from the end.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Breadth-first Search": https://leetcode.com/tag/breadth-first-search Similar Questions: "Word Ladder II": https://leetcode.com/problems/word-ladder-ii "Minimum Genetic Mutation": https://leetcode.com/problems/minimum-genetic-mutation
Problem:
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
Example 1:
Example 2:
Solution:
Think of it as building a tree, with begineWord
as root and endWord
as leaves.
The best way control the depth (length of the shortest transformations) while building the tree is level-order traversal (BFS).
We do not actually build the tree because it is expensive (astronomical if the list is huge). In fact, we only need one shortest path. So just like Dijkstra's algorithm, we say that the first time (level i
) we encounter a word that turns out to be in a shortest path, then level i
is the lowest level this word could ever get. We can safely remove it from the wordList
.
To find all the next words, instead of filtering the wordList
, enumerate all 25 possible words and check if in wordList
.
Template generated via Leetmark.
Difficulty: Hard Related Topics: "Array": https://leetcode.com/tag/array "Union Find": https://leetcode.com/tag/union-find Similar Questions: "Binary Tree Longest Consecutive Sequence": https://leetcode.com/problems/binary-tree-longest-consecutive-sequence
Problem:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Solution:
Build a Set from the list. Pick a number, find all it's adjacent numbers that are also in the Set. Count them and remove them all from the Set. Repeat until the Set is empty. Time complexity O(n + n) = O(n).
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Tree": https://leetcode.com/tag/tree "Depth-first Search": https://leetcode.com/tag/depth-first-search Similar Questions: "Path Sum": https://leetcode.com/problems/path-sum "Binary Tree Maximum Path Sum": https://leetcode.com/problems/binary-tree-maximum-path-sum
Problem:
Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which represents the number 123
.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
Example 2:
Solution:
To write a clean solution for this promblem, use 0
as indicator of leaf node. If all the children get 0
, it is a leaf node, return the sum of current level.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Depth-first Search": https://leetcode.com/tag/depth-first-search "Breadth-first Search": https://leetcode.com/tag/breadth-first-search "Union Find": https://leetcode.com/tag/union-find Similar Questions: "Number of Islands": https://leetcode.com/problems/number-of-islands "Walls and Gates": https://leetcode.com/problems/walls-and-gates
Problem:
Given a 2D board containing 'X'
and 'O'
(the letter O), capture all regions surrounded by 'X'
.
A region is captured by flipping all 'O'
s into 'X'
s in that surrounded region.
Example:
After running your function, the board should be:
Explanation:
Surrounded regions shouldn't be on the border, which means that any 'O'
on the border of the board are not flipped to 'X'
. Any 'O'
that is not on the border and it is not connected to an 'O'
on the border will be flipped to 'X'
. Two cells are connected if they are adjacent cells connected horizontally or vertically.
Solution:
Find all the O
s that are connected to the O
s on the border, change them to #
. Then scan the board, change O
to X
and #
back to O
.
The process of finding the connected O
s is just like tree traversal. O
s on the border are the same level. Their children are the second level. And so on.
So both BFS and DFS are good. I prefer BFS when pruning is not needed in favor of its readability.
Template generated via Leetmark.
Difficulty: Medium Related Topics: "Depth-first Search": https://leetcode.com/tag/depth-first-search "Breadth-first Search": https://leetcode.com/tag/breadth-first-search "Graph": https://leetcode.com/tag/graph Similar Questions: "Copy List with Random Pointer": https://leetcode.com/problems/copy-list-with-random-pointer
Problem:
Given the head of a graph, return a deep copy (clone) of the graph. Each node in the graph contains a label
(int
) and a list (List[UndirectedGraphNode]
) of its neighbors
. There is an edge between the given node and each of the nodes in its neighbors.
OJ's undirected graph serialization (so you can understand error output):
Nodes are labeled uniquely.
We use #
as a separator for each node, and ,
as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}
.
The graph has a total of three nodes, and therefore contains three parts as separated by #
.
First node is labeled as
0
. Connect node0
to both nodes1
and2
.Second node is labeled as
1
. Connect node1
to node2
.Third node is labeled as
2
. Connect node2
to node2
(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
Note: The information about the tree serialization is only meant so that you can understand error output if you get a wrong answer. You don't need to understand the serialization to solve the problem.
Solution:
DFS. Cache the visited node before entering the next recursion.
Template generated via Leetmark.
Balanced Binary Tree - LeetCode
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.
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Input: root =3,9,20,null,null,15,73,9,20,null,null,15,7 Output: true
Example 2:
Input: root =1,2,2,3,3,null,null,4,41,2,2,3,3,null,null,4,4 Output: false
Example 3:
Input: root = [] Output: true
Constraints:
The number of nodes in the tree is in the range
[0, 5000]
.-104 <= Node.val <= 104
Source# Convert Sorted Array to Binary Search Tree
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.
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array:-10,-3,0,5,9−10,−3,0,5,9,
One possible answer is:0,-3,9,-10,null,50,−3,9,−10,null,5, which represents the following height balanced BST:
-3 9 / / -10 5
Source# Delete Node in a BST
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.
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Follow up: Can you solve it with time complexity O(height of tree)
?
Example 1:
Example 2:
Input: root =5,3,6,2,4,null,75,3,6,2,4,null,7, key = 0 **Output:**5,3,6,2,4,null,75,3,6,2,4,null,7 Explanation: The tree does not contain a node with value = 0.
Example 3:
Input: root = [], key = 0 Output: []
Constraints:
The number of nodes in the tree is in the range
[0, 104]
.-105 <= Node.val <= 105
Each node has a unique value.
root
is a valid binary search tree.-105 <= key <= 105
≡
Last updated