Leetcode Flashcards
(379 cards)
Two Sum
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target.
- Use
Map
to save already seen elements - Iterate through
nums
- If
target - nums[i]
exists inMap
–> return
O(n) time
O(n) space
Valid Parentheses
Given a string s
containing just the characters (
, )
, {
, }
, [
and ]
, determine if the input string is valid.
- Use
Stack
to push opened brackets - For closed –
pop()
(checkisEmpty()
first!) - Check if pair is valid
- If
Stack
is not empty – returnfalse
elsetrue
O(n) time
O(n) space
Merge Two Sorted Lists
You are given the heads of two sorted linked lists list1
and list2
. Merge the two lists in a one sorted list.
- Create an empty
Node
ashead
while (list1 != null && list2 != null)
while (list1 != null)
while (list2 != null)
- Return
head.next
O(m + n) time
O(m + n) space
Best Time to Buy and Sell Stock
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction.
- Keep track of a min seen value
- Compute profit for each
price
:price[i] - min
- Update
maxProfit
O(n) time
O(1) space
Valid Palindrome
Given a string s
, return true
if it is a palindrome, or false
otherwise.
while (left < right)
- If
!=
->false
- Return
true
O(n) time
O(1) space
Invert Binary Tree
Given the root
of a binary tree, invert the tree, and return its root.
- Recursive
swap(Node root)
- If
root == null
return - Swap
left
andright
swap(root.left)
swap(root.right)
O(n) time
O(n) space
Valid Anagram
Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
- Create a char
Map
for each word - If maps are equal ->
true
O(m + n) time
O(m + n) space
Binary Search
Given an array of integers nums
which is sorted in ascending order, and an integer target
, write a function to search target
in nums
. If target exists, then return its index. Otherwise, return -1
.
-
while (left <= right)
2 .mid = (left + right) / 2
- Greater ->
left = mid + 1
- Less ->
right = mid - 1
- Equal -> return
mid
O(log n) time
O(1) space
Flood Fill
An image is represented by an m x n
integer grid image
where image[i][j]
represents the pixel value of the image.
You are also given three integers sr
, sc
, and color
. You should perform a flood fill on the image starting from the pixel image[sr][sc]
.
To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.
- Recursive
recolor(int[][] image, int x, int y, int oldColor, int newColor)
- If out of bounds or already recolored -> return
- Change color
- Call
recolor()
four times for all directions
O(n) time
O(n) space
Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p
and q
as the lowest node in T
that has both p
and q
as descendants (where we allow a node to be a descendant of itself).”
- Recursive
find(Node root, Node p, Node q)
- If
p
andq
are of different sides -> returnroot
- If
p == root
orq == root
-> returnroot
- If both on the left – search left subtree
- If both on the right – search right subtree
O(log n) time
O(lon n) space
Balanced Binary Tree
Given a binary tree, determine if it is
height-balanced.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
- Recursive
height(TreeNode root, int height)
- If
Math.abs(left - right) > 1
-> return-1
- Return
Math.max(left, right)
O(n) time
O(n) space
Linked List Cycle
Given head
, the head of a linked list, determine if the linked list has a cycle in it.
- Use fast and slow pointers
while (fast != null && fast.next != null)
- If
fast == slow
-> returntrue
O(n) time
O(1) space
Implement Queue using Stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push
, peek
, pop
, and empty
).
-
push()
to firstStack
- On
pop()
andpeek()
return from secondStack
- If second
Stack
is empty – transfer elements from first to second
O(n) time for push and pop
O(n) space
First Bad Version
Suppose you have n
versions [1, 2, ..., n]
and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version)
which returns whether version
is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
- Binary search
-
int mid = left + (right - left) / 2
(not to overflowint
!) - If
mid
is bad – search on the left - Return
left
O(log n) time
O(1) space
Ransom Note
Given two strings ransomNote
and magazine
, return true
if ransomNote
can be constructed by using the letters from magazine
and false
otherwise.
- Create char
Map
of amagazine
- Iterate through
ransomNote
- If
ransomNote[i]
does not exist inMap
->false
- Lower the counter in
Map
as the char was used - Return
true
O(m + n) time
O(1) space
Climbing Stairs
You are climbing a staircase. It takes n
steps to reach the top.
Each time you can either climb 1
or 2
steps. In how many distinct ways can you climb to the top?
- Go from top to bottom
- Recursive
count(int n)
with memoization memo.put(1, 1); memo.put(2, 2)
count = count(n - 1) + count(n - 2)
- If is in
memo
-> return - Else put in
memo
-> returncount
O(n) time
O(n) space
Longest Palindrome
Given a string s
which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
- Create a char
Map
- If
count % 2 == 0
->maxLength += 2
- If
maxLength < s.length()
->maxLength += 1
(for cases likeaca
,abeba
, etc.
O(n) time
O(1) space
Reverse Linked List
Given the head
of a singly linked list, reverse the list, and return the reversed list.
Node prev = null
while (head != null) {
Node next = head.next
head.next = prev
prev = head
head = next
}
O(n) time
O(1) space
Majority Element
Given an array nums
of size n
, return the majority element.
The majority element is the element that appears more than [n / 2]
times. You may assume that the majority element always exists in the array.
Sort and return mid
OR
- Take first element as a
candidate
- Iterate through
nums
- If
count == 0
->candidate = nums[i]
- If
nums[i] == candidate
->count++
- Else
count--
- Return
candidate
O(n) time
O(1) space
Add Binary
Given two binary strings a
and b
, return their sum as a binary string.
- Two pointers from the end of each string
- Init
carry = 0
- Iterate backwards while both pointers
>= 0
result.append(sum % 2)
carry = sum / 2
- Return
result.reverse().toString()
O(n) time
O(1) space
Diameter of Binary Tree
Given the root
of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root
.
The length of a path between two nodes is represented by the number of edges between them.
- Recursive
heightAndDiameter(Node root)
- If
root == null
->Pair(0, 0)
- Call for
left
andright
maxHeight = max(left.height, right.height) + 1
maxDiameter = max(left.height + right.height, max(left.diameter, right.diameter)
- Return
Pair(maxHeight, maxDiameter)
O(n) time
O(n) space
Middle of the Linked List
Given the head
of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
- Fast and slow pointers
- Return slow
O(n) time
O(1) space
Maximum Depth of Binary Tree
Given the root
of a binary tree, return its maximum depth.
A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
- Recursive
depth(Node root)
- If
root == null
->0
- Return
max(left, right) + 1
O(n) time
O(n) space
Contains Duplicate
Given an integer array nums
, return true
if any value appears at least twice in the array, and return false
if every element is distinct.
- Use
Set
of already seen elements - If
seen.contains(nums[i])
->false
- Return
true
O(n) time
O(n) space
- > result)`
2. If `root == null` -> return
3. If `(level >= result.size()` -> `add(new ArrayList<>())`
4. `result.get(level).add(root.val)`
5. `traverse(root.left, level + 1, result)`
6. `traverse(root.right, level + 1, result)`
**O(n) time**
**O(n) space**
- > result)`
2. `add()`
3. For each `nums[i]` starting from `start` -> `backtrack(i + 1)`
**O(2^n) time**
**O(2^n) space**
- > result)`
2. If `tmp.size() == nums.length` -> `add()` and return
3. If `used[i]` or `i > 0 && nums[i] = nums[i - 1] && !used[i - 1]` -> `continue`
4. `tmp.add(nums[i]); used[i] = 1; backtrack(); tmp.remove(N - 1); used[i] = 0`
**O(n!) time**
**O(n!) space**
- > result)`
2. `add()`
3. If `i > start && nums[i] == nums[i - 1]` -> `continue`
4. `tmp.add(nums[i]); backtrack(i + 1); tmp.remove(N - 1)`
**O(2^n) time**
**O(2^n) space**
- result)`
2. If `remains < 0` -> return
3. If `remains == 0` -> `add()` and return
4. if `i > start && candidates[i] == candidates[i - 1]` -> `continue`
5. `tmp.add(nums[i]); backtrack(i + 1); tmp.remove(N - 1)`
**O(2^n) time**
**O(2^n) space**
- > result)`
2. If `root == null` -> return `false`
3. `currentPath.add(root.val)`
4. If `root.right == null && root.left == null && remains == root.val` -> `add()`
5. Else `backtrack(left, remains - root.val); backtrack(right, remains - root.val)`
6. `currentPath.remove(N - 1)`
**O(n) time**
**O(n) space**