Neetcode150 Java Solutions
Neetcode150 Java Solutions
Valid Anagram
Difficulty: Easy
class Solution {
public boolean isAnagram(String s, String t) {
if ([Link]() != [Link]()) return false;
int[] count = new int[26];
for (char c : [Link]()) count[c - 'a']++;
for (char c : [Link]()) count[c - 'a']--;
for (int v : count) if (v != 0) return false;
return true;
}
}
Two Sum
Difficulty: Easy
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < [Link]; i++) {
int comp = target - nums[i];
if ([Link](comp)) return new int[]{[Link](comp), i};
[Link](nums[i], i);
}
return new int[]{};
}
}
Group Anagrams
Difficulty: Medium
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] arr = [Link]();
[Link](arr);
String key = new String(arr);
[Link](key, k -> new ArrayList<>()).add(s);
}
return new ArrayList<>([Link]());
}
}
Valid Sudoku
Difficulty: Medium
class Solution {
public boolean isValidSudoku(char[][] board) {
Set<String> seen = new HashSet<>();
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
char ch = board[r][c];
if (ch == '.') continue;
String row = "r" + r + ch, col = "c" + c + ch;
String box = "b" + (r/3) + (c/3) + ch;
if ( ||  || )
return false;
}
}
return true;
}
}
3Sum
Difficulty: Medium
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
[Link](nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < [Link] - 2; i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;
int l = i+1, r = [Link] - 1;
while (l < r) {
int s = nums[i] + nums[l] + nums[r];
if (s == 0) {
[Link]([Link](nums[i], nums[l], nums[r]));
while (l < r && nums[l] == nums[l+1]) l++;
while (l < r && nums[r] == nums[r-1]) r--;
l++; r--;
} else if (s < 0) l++;
else r--;
}
}
return res;
}
}
Sliding Window
Best Time to Buy and Sell Stock
Difficulty: Easy
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE, maxProfit = 0;
for (int p : prices) {
minPrice = [Link](minPrice, p);
maxProfit = [Link](maxProfit, p - minPrice);
}
return maxProfit;
}
}
Permutation in String
Difficulty: Medium
class Solution {
public boolean checkInclusion(String s1, String s2) {
int[] c1 = new int[26], c2 = new int[26];
for (char c : [Link]()) c1[c-'a']++;
for (int i = 0; i < [Link](); i++) {
c2[[Link](i)-'a']++;
if (i >= [Link]()) c2[[Link]([Link]())-'a']--;
if ([Link](c1, c2)) return true;
}
return false;
}
}
Stack
Valid Parentheses
Difficulty: Easy
class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : [Link]()) {
if (c=='(' || c=='{' || c=='[') [Link](c);
else {
if ([Link]()) return false;
char top = [Link]();
if (c==')' && top!='(') return false;
if (c=='}' && top!='{') return false;
if (c==']' && top!='[') return false;
}
}
return [Link]();
}
}
Min Stack
Difficulty: Medium
class MinStack {
private Deque<int[]> stack = new ArrayDeque<>();
public void push(int val) {
int min = [Link]() ? val : [Link](val, [Link]()[1]);
[Link](new int[]{val, min});
}
public void pop() { [Link](); }
public int top() { return [Link]()[0]; }
public int getMin() { return [Link]()[1]; }
}
Generate Parentheses
Difficulty: Medium
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
backtrack(res, "", 0, 0, n);
return res;
}
void backtrack(List<String> res, String s, int open, int close, int n) {
if ([Link]() == 2*n) { [Link](s); return; }
if (open < n) backtrack(res, s+"(", open+1, close, n);
if (close < open) backtrack(res, s+")", open, close+1, n);
}
}
Daily Temperatures
Difficulty: Medium
class Solution {
public int[] dailyTemperatures(int[] temps) {
int n = [Link];
int[] res = new int[n];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
while (![Link]() && temps[i] > temps[[Link]()]) {
int idx = [Link]();
res[idx] = i - idx;
}
[Link](i);
}
return res;
}
}
Car Fleet
Difficulty: Medium
class Solution {
public int carFleet(int target, int[] pos, int[] speed) {
int n = [Link];
double[][] cars = new double[n][2];
for (int i = 0; i < n; i++) cars[i] = new double[]{pos[i], (double)(target-pos[i])/speed[i]};
[Link](cars, (a,b) -> [Link](b[0], a[0]));
int fleets = 0;
double maxTime = 0;
for (double[] car : cars) {
if (car[1] > maxTime) { fleets++; maxTime = car[1]; }
}
return fleets;
}
}
Binary Search
Binary Search
Difficulty: Easy
class Solution {
public int search(int[] nums, int target) {
int l = 0, r = [Link] - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] < target) l = mid + 1;
else r = mid - 1;
}
return -1;
}
}
Search a 2D Matrix
Difficulty: Medium
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = [Link], n = matrix[0].length;
int l = 0, r = m*n - 1;
while (l <= r) {
int mid = l + (r-l)/2;
int val = matrix[mid/n][mid%n];
if (val == target) return true;
else if (val < target) l = mid+1;
else r = mid-1;
}
return false;
}
}
Linked List
Reverse Linked List
Difficulty: Easy
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null, cur = head;
while (cur != null) {
ListNode next = [Link];
[Link] = prev;
prev = cur;
cur = next;
}
return prev;
}
}
Reorder List
Difficulty: Medium
class Solution {
public void reorderList(ListNode head) {
// Find middle
ListNode slow=head, fast=[Link];
while (fast != null && [Link] != null) { slow=[Link]; fast=[Link]; }
// Reverse second half
ListNode second=[Link], prev=null; [Link]=null;
while (second != null) { ListNode tmp=[Link]; [Link]=prev; prev=second; second=tmp; }
// Merge
ListNode first=head; second=prev;
while (second != null) {
ListNode t1=[Link], t2=[Link];
[Link]=second; [Link]=t1;
first=t1; second=t2;
}
}
}
LRU Cache
Difficulty: Medium
class LRUCache {
private final int cap;
private final Map<Integer, Integer> map;
public LRUCache(int capacity) {
[Link] = capacity;
[Link] = new LinkedHashMap<>(capacity, 0.75f, true) {
protected boolean removeEldestEntry([Link] e) { return size() > cap; }
};
}
public int get(int key) { return [Link](key, -1); }
public void put(int key, int value) { [Link](key, value); }
}
Trees
Invert Binary Tree
Difficulty: Easy
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
TreeNode tmp = [Link];
[Link] = invertTree([Link]);
[Link] = invertTree(tmp);
return root;
}
}
Same Tree
Difficulty: Easy
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null || [Link] != [Link]) return false;
return isSameTree([Link], [Link]) && isSameTree([Link], [Link]);
}
}
Task Scheduler
Difficulty: Medium
class Solution {
public int leastInterval(char[] tasks, int n) {
int[] freq = new int[26];
for (char c : tasks) freq[c-'A']++;
int maxFreq = [Link](freq).max().getAsInt();
long maxCount = [Link](freq).filter(f->f==maxFreq).count();
return (int)[Link]([Link], (maxFreq-1)*(n+1)+maxCount);
}
}
Design Twitter
Difficulty: Medium
class Twitter {
private Map<Integer,Set<Integer>> following = new HashMap<>();
private List<int[]> tweets = new ArrayList<>();
private int time = 0;
public void postTweet(int userId, int tweetId) { [Link](new int[]{userId,tweetId,time++}); }
public List<Integer> getNewsFeed(int userId) {
Set<Integer> fl = [Link](userId, new HashSet<>());
return [Link]().filter(t->t[0]==userId||[Link](t[0]))
.sorted((a,b)->b[2]-a[2]).limit(10).map(t->t[1])
.collect([Link]());
}
public void follow(int f, int e) { [Link](f,k->new HashSet<>()).add(e); }
public void unfollow(int f, int e) { if ([Link](f)) [Link](f).remove(e); }
}
Backtracking
Subsets
Difficulty: Medium
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
backtrack(res, new ArrayList<>(), nums, 0);
return res;
}
void backtrack(List<List<Integer>> res, List<Integer> curr, int[] nums, int start) {
[Link](new ArrayList<>(curr));
for (int i = start; i < [Link]; i++) {
[Link](nums[i]);
backtrack(res, curr, nums, i+1);
[Link]([Link]()-1);
}
}
}
Combination Sum
Difficulty: Medium
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
backtrack(res, new ArrayList<>(), candidates, target, 0);
return res;
}
void backtrack(List<List<Integer>> res, List<Integer> curr, int[] cands, int remain, int start) {
if (remain == 0) { [Link](new ArrayList<>(curr)); return; }
for (int i = start; i < [Link]; i++) {
if (cands[i] <= remain) {
[Link](cands[i]);
backtrack(res, curr, cands, remain-cands[i], i);
[Link]([Link]()-1);
}
}
}
}
Permutations
Difficulty: Medium
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
backtrack(res, new ArrayList<>(), nums);
return res;
}
void backtrack(List<List<Integer>> res, List<Integer> curr, int[] nums) {
if ([Link]() == [Link]) { [Link](new ArrayList<>(curr)); return; }
for (int n : nums) {
if () {
[Link](n);
backtrack(res, curr, nums);
[Link]([Link]()-1);
}
}
}
}
Subsets II
Difficulty: Medium
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
[Link](nums);
List<List<Integer>> res = new ArrayList<>();
backtrack(res, new ArrayList<>(), nums, 0);
return res;
}
void backtrack(List<List<Integer>> res, List<Integer> curr, int[] nums, int start) {
[Link](new ArrayList<>(curr));
for (int i = start; i < [Link]; i++) {
if (i > start && nums[i] == nums[i-1]) continue;
[Link](nums[i]);
backtrack(res, curr, nums, i+1);
[Link]([Link]()-1);
}
}
}
Combination Sum II
Difficulty: Medium
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
[Link](candidates);
List<List<Integer>> res = new ArrayList<>();
backtrack(res, new ArrayList<>(), candidates, target, 0);
return res;
}
void backtrack(List<List<Integer>> res, List<Integer> curr, int[] cands, int remain, int start) {
if (remain == 0) { [Link](new ArrayList<>(curr)); return; }
for (int i = start; i < [Link]; i++) {
if (i > start && cands[i] == cands[i-1]) continue;
if (cands[i] > remain) break;
[Link](cands[i]);
backtrack(res, curr, cands, remain-cands[i], i+1);
[Link]([Link]()-1);
}
}
}
Word Search
Difficulty: Medium
class Solution {
public boolean exist(char[][] board, String word) {
int m=[Link], n=board[0].length;
for (int i=0;i<m;i++) for (int j=0;j<n;j++)
if (dfs(board,word,i,j,0)) return true;
return false;
}
boolean dfs(char[][] b, String w, int r, int c, int idx) {
if (idx==[Link]()) return true;
if (r<0||r>=[Link]||c<0||c>=b[0].length||b[r][c]!=[Link](idx)) return false;
char tmp=b[r][c]; b[r][c]='#';
boolean found=dfs(b,w,r+1,c,idx+1)||dfs(b,w,r-1,c,idx+1)||
dfs(b,w,r,c+1,idx+1)||dfs(b,w,r,c-1,idx+1);
b[r][c]=tmp;
return found;
}
}
Palindrome Partitioning
Difficulty: Medium
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
backtrack(res, new ArrayList<>(), s, 0);
return res;
}
void backtrack(List<List<String>> res, List<String> curr, String s, int start) {
if (start == [Link]()) { [Link](new ArrayList<>(curr)); return; }
for (int end = start+1; end <= [Link](); end++) {
String sub = [Link](start, end);
if (isPalin(sub)) {
[Link](sub);
backtrack(res, curr, s, end);
[Link]([Link]()-1);
}
}
}
boolean isPalin(String s) {
int l=0,r=[Link]()-1;
while(l<r) if([Link](l++)!=[Link](r--)) return false;
return true;
}
}
N-Queens
Difficulty: Hard
class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<>();
char[][] board = new char[n][n];
for (char[] row : board) [Link](row, '.');
Set<Integer> cols=new HashSet<>(), diag1=new HashSet<>(), diag2=new HashSet<>();
solve(board, 0, cols, diag1, diag2, res);
return res;
}
void solve(char[][] board, int row, Set<Integer> cols, Set<Integer> d1, Set<Integer> d2, List<List<String>> res) {
if (row==[Link]) {
List<String> r=new ArrayList<>();
for (char[] row2:board) [Link](new String(row2));
[Link](r); return;
}
for (int col=0;col<[Link];col++) {
if ([Link](col)||[Link](row-col)||[Link](row+col)) continue;
board[row][col]='Q'; [Link](col); [Link](row-col); [Link](row+col);
solve(board,row+1,cols,d1,d2,res);
board[row][col]='.'; [Link](col); [Link](row-col); [Link](row+col);
}
}
}
Tries
Implement Trie (Prefix Tree)
Difficulty: Medium
class Trie {
private Trie[] children = new Trie[26];
private boolean isEnd = false;
public void insert(String word) {
Trie cur = this;
for (char c : [Link]()) {
int i = c - 'a';
if ([Link][i] == null) [Link][i] = new Trie();
cur = [Link][i];
}
[Link] = true;
}
public boolean search(String word) {
Trie node = find(word);
return node != null && [Link];
}
public boolean startsWith(String prefix) { return find(prefix) != null; }
private Trie find(String s) {
Trie cur = this;
for (char c : [Link]()) {
if ([Link][c-'a'] == null) return null;
cur = [Link][c-'a'];
}
return cur;
}
}
Word Search II
Difficulty: Hard
class Solution {
public List<String> findWords(char[][] board, String[] words) {
Trie root = new Trie();
for (String w : words) [Link](w);
List<String> res = new ArrayList<>();
int m=[Link], n=board[0].length;
for (int i=0;i<m;i++) for (int j=0;j<n;j++)
dfs(board, root, i, j, res);
return res;
}
void dfs(char[][] b, Trie node, int r, int c, List<String> res) {
if (r<0||r>=[Link]||c<0||c>=b[0].length||b[r][c]=='#') return;
char ch=b[r][c]; Trie next=[Link][ch-'a'];
if (next==null) return;
if ([Link]!=null) { [Link]([Link]); [Link]=null; }
b[r][c]='#';
dfs(b,next,r+1,c,res); dfs(b,next,r-1,c,res);
dfs(b,next,r,c+1,res); dfs(b,next,r,c-1,res);
b[r][c]=ch;
}
}
class Trie {
Trie[] children=new Trie[26]; String word;
void insert(String w) {
Trie cur=this;
for (char c:[Link]()) { if([Link][c-'a']==null)[Link][c-'a']=new Trie(); cur=[Link][c-'a
[Link]=w;
}
}
Graphs
Number of Islands
Difficulty: Medium
class Solution {
public int numIslands(char[][] grid) {
int count = 0;
for (int r=0;r<[Link];r++) for (int c=0;c<grid[0].length;c++)
if (grid[r][c]=='1') { dfs(grid,r,c); count++; }
return count;
}
void dfs(char[][] grid, int r, int c) {
if (r<0||r>=[Link]||c<0||c>=grid[0].length||grid[r][c]!='1') return;
grid[r][c]='0';
dfs(grid,r+1,c); dfs(grid,r-1,c); dfs(grid,r,c+1); dfs(grid,r,c-1);
}
}
Clone Graph
Difficulty: Medium
class Solution {
Map<Node,Node> map = new HashMap<>();
public Node cloneGraph(Node node) {
if (node==null) return null;
if ([Link](node)) return [Link](node);
Node clone = new Node([Link]);
[Link](node, clone);
for (Node n : [Link]) [Link](cloneGraph(n));
return clone;
}
}
Rotting Oranges
Difficulty: Medium
class Solution {
public int orangesRotting(int[][] grid) {
Queue<int[]> q = new LinkedList<>();
int fresh=0;
for (int r=0;r<[Link];r++) for (int c=0;c<grid[0].length;c++) {
if (grid[r][c]==2) [Link](new int[]{r,c});
else if (grid[r][c]==1) fresh++;
}
int[][] dirs={{1,0},{-1,0},{0,1},{0,-1}}; int min=0;
while (![Link]() && fresh>0) {
min++;
for (int size=[Link]();size>0;size--) {
int[] pos=[Link]();
for (int[] d:dirs) {
int nr=pos[0]+d[0],nc=pos[1]+d[1];
if (nr<0||nr>=[Link]||nc<0||nc>=grid[0].length||grid[nr][nc]!=1) continue;
grid[nr][nc]=2; fresh--; [Link](new int[]{nr,nc});
}
}
}
return fresh==0?min:-1;
}
}
Surrounded Regions
Difficulty: Medium
class Solution {
public void solve(char[][] board) {
int m=[Link], n=board[0].length;
for (int r=0;r<m;r++) { dfs(board,r,0); dfs(board,r,n-1); }
for (int c=0;c<n;c++) { dfs(board,0,c); dfs(board,m-1,c); }
for (int r=0;r<m;r++) for (int c=0;c<n;c++) {
if (board[r][c]=='O') board[r][c]='X';
else if (board[r][c]=='S') board[r][c]='O';
}
}
void dfs(char[][] b, int r, int c) {
if (r<0||r>=[Link]||c<0||c>=b[0].length||b[r][c]!='O') return;
b[r][c]='S';
dfs(b,r+1,c); dfs(b,r-1,c); dfs(b,r,c+1); dfs(b,r,c-1);
}
}
Course Schedule
Difficulty: Medium
class Solution {
public boolean canFinish(int n, int[][] prerequisites) {
List<List<Integer>> adj = new ArrayList<>();
for (int i=0;i<n;i++) [Link](new ArrayList<>());
for (int[] p:prerequisites) [Link](p[1]).add(p[0]);
int[] state = new int[n]; // 0=unvis, 1=visiting, 2=done
for (int i=0;i<n;i++) if (!dfs(adj,state,i)) return false;
return true;
}
boolean dfs(List<List<Integer>> adj, int[] state, int node) {
if (state[node]==1) return false;
if (state[node]==2) return true;
state[node]=1;
for (int nei:[Link](node)) if (!dfs(adj,state,nei)) return false;
state[node]=2;
return true;
}
}
Course Schedule II
Difficulty: Medium
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
List<List<Integer>> adj = new ArrayList<>();
for (int i=0;i<numCourses;i++) [Link](new ArrayList<>());
for (int[] p:prerequisites) [Link](p[1]).add(p[0]);
int[] state=new int[numCourses];
List<Integer> order = new ArrayList<>();
for (int i=0;i<numCourses;i++) if (!dfs(adj,state,i,order)) return new int[]{};
[Link](order);
return [Link]().mapToInt(Integer::intValue).toArray();
}
boolean dfs(List<List<Integer>> adj,int[] state,int node,List<Integer> order) {
if (state[node]==1) return false;
if (state[node]==2) return true;
state[node]=1;
for (int nei:[Link](node)) if (!dfs(adj,state,nei,order)) return false;
state[node]=2; [Link](node);
return true;
}
}
Redundant Connection
Difficulty: Medium
class Solution {
public int[] findRedundantConnection(int[][] edges) {
int n=[Link];
int[] parent=new int[n+1];
for (int i=0;i<=n;i++) parent[i]=i;
for (int[] e:edges) {
int p1=find(parent,e[0]), p2=find(parent,e[1]);
if (p1==p2) return e;
parent[p1]=p2;
}
return new int[]{};
}
int find(int[] p, int x) { return p[x]==x?x:(p[x]=find(p,p[x])); }
}
Word Ladder
Difficulty: Hard
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> wordSet = new HashSet<>(wordList);
if () return 0;
Queue<String> q = new LinkedList<>();
[Link](beginWord); int steps=1;
Set<String> visited = new HashSet<>(); [Link](beginWord);
while (![Link]()) {
for (int size=[Link]();size>0;size--) {
String word=[Link]();
if ([Link](endWord)) return steps;
char[] arr=[Link]();
for (int i=0;i<[Link];i++) {
char orig=arr[i];
for (char c='a';c<='z';c++) {
arr[i]=c; String next=new String(arr);
if ([Link](next)&&) { [Link](next); [Link](next); }
}
arr[i]=orig;
}
}
steps++;
}
return 0;
}
}
Advanced Graphs
Reconstruct Itinerary
Difficulty: Hard
class Solution {
public List<String> findItinerary(List<List<String>> tickets) {
Map<String, PriorityQueue<String>> adj = new HashMap<>();
for (List<String> t:tickets) [Link]([Link](0),k->new PriorityQueue<>()).offer([Link](1));
LinkedList<String> res=new LinkedList<>();
dfs("JFK", adj, res);
return res;
}
void dfs(String airport, Map<String,PriorityQueue<String>> adj, LinkedList<String> res) {
PriorityQueue<String> next=[Link](airport);
while (next!=null && ![Link]()) dfs([Link](),adj,res);
[Link](airport);
}
}
Min Cost to Connect All Points
Difficulty: Medium
class Solution {
public int minCostConnectPoints(int[][] points) {
int n=[Link], total=0, edges=0;
boolean[] inMST=new boolean[n];
int[] minCost=new int[n]; [Link](minCost,Integer.MAX_VALUE); minCost[0]=0;
while (edges<n) {
int u=-1;
for (int i=0;i<n;i++) if (!inMST[i]&&(u==-1||minCost[i]<minCost[u])) u=i;
inMST[u]=true; total+=minCost[u]; edges++;
for (int v=0;v<n;v++) if (!inMST[v]) {
int cost=[Link](points[u][0]-points[v][0])+[Link](points[u][1]-points[v][1]);
minCost[v]=[Link](minCost[v],cost);
}
}
return total;
}
}
Alien Dictionary
Difficulty: Hard
class Solution {
public String alienOrder(String[] words) {
Map<Character,Set<Character>> adj=new HashMap<>();
Map<Character,Integer> indegree=new HashMap<>();
for (String w:words) for (char c:[Link]()) { [Link](c,new HashSet<>()); [Link](c,0); }
for (int i=0;i<[Link]-1;i++) {
String w1=words[i],w2=words[i+1];
int len=[Link]([Link](),[Link]()); boolean found=false;
for (int j=0;j<len;j++) {
if ([Link](j)!=[Link](j)) {
if ().contains([Link](j))) {
[Link]([Link](j)).add([Link](j));
[Link]([Link](j),1,Integer::sum);
}
found=true; break;
}
}
if (!found&&[Link]()>[Link]()) return "";
}
Queue<Character> q=new LinkedList<>();
for (char c:[Link]()) if ([Link](c)==0) [Link](c);
StringBuilder sb=new StringBuilder();
while (![Link]()) {
char c=[Link](); [Link](c);
for (char nei:[Link](c)) { [Link](nei,-1,Integer::sum); if ([Link](nei)==0) [Link](nei); }
}
return [Link]()==[Link]()?[Link]():"";
}
}
House Robber
Difficulty: Medium
class Solution {
public int rob(int[] nums) {
int prev=0, cur=0;
for (int n:nums) { int tmp=[Link](cur, prev+n); prev=cur; cur=tmp; }
return cur;
}
}
House Robber II
Difficulty: Medium
class Solution {
public int rob(int[] nums) {
if ([Link]==1) return nums[0];
return [Link](robRange(nums,0,[Link]-2), robRange(nums,1,[Link]-1));
}
int robRange(int[] nums, int l, int r) {
int prev=0, cur=0;
for (int i=l;i<=r;i++) { int tmp=[Link](cur,prev+nums[i]); prev=cur; cur=tmp; }
return cur;
}
}
Palindromic Substrings
Difficulty: Medium
class Solution {
public int countSubstrings(String s) {
int count=0;
for (int i=0;i<[Link]();i++) {
count+=expand(s,i,i);
count+=expand(s,i,i+1);
}
return count;
}
int expand(String s, int l, int r) {
int count=0;
while (l>=0&&r<[Link]()&&[Link](l)==[Link](r)) { count++; l--; r++; }
return count;
}
}
Decode Ways
Difficulty: Medium
class Solution {
public int numDecodings(String s) {
int n=[Link](), prev2=1, prev1=[Link](0)!='0'?1:0;
for (int i=1;i<n;i++) {
int cur=0;
if ([Link](i)!='0') cur=prev1;
int two=[Link]([Link](i-1,i+1));
if (two>=10&&two<=26) cur+=prev2;
prev2=prev1; prev1=cur;
}
return prev1;
}
}
Coin Change
Difficulty: Medium
class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp=new int[amount+1]; [Link](dp,amount+1); dp[0]=0;
for (int i=1;i<=amount;i++) for (int c:coins) if (c<=i) dp[i]=[Link](dp[i],dp[i-c]+1);
return dp[amount]>amount?-1:dp[amount];
}
}
Word Break
Difficulty: Medium
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> dict=new HashSet<>(wordDict);
boolean[] dp=new boolean[[Link]()+1]; dp[0]=true;
for (int i=1;i<=[Link]();i++)
for (int j=0;j<i;j++)
if (dp[j]&&[Link]([Link](j,i))) { dp[i]=true; break; }
return dp[[Link]()];
}
}
Coin Change II
Difficulty: Medium
class Solution {
public int change(int amount, int[] coins) {
int[] dp=new int[amount+1]; dp[0]=1;
for (int c:coins) for (int j=c;j<=amount;j++) dp[j]+=dp[j-c];
return dp[amount];
}
}
Target Sum
Difficulty: Medium
class Solution {
public int findTargetSumWays(int[] nums, int target) {
Map<Integer,Integer> dp=new HashMap<>(); [Link](0,1);
for (int n:nums) {
Map<Integer,Integer> next=new HashMap<>();
for (int sum:[Link]()) {
[Link](sum+n,[Link](sum),Integer::sum);
[Link](sum-n,[Link](sum),Integer::sum);
}
dp=next;
}
return [Link](target,0);
}
}
Interleaving String
Difficulty: Medium
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int m=[Link](), n=[Link]();
if (m+n!=[Link]()) return false;
boolean[][] dp=new boolean[m+1][n+1]; dp[0][0]=true;
for (int i=1;i<=m;i++) dp[i][0]=dp[i-1][0]&&[Link](i-1)==[Link](i-1);
for (int j=1;j<=n;j++) dp[0][j]=dp[0][j-1]&&[Link](j-1)==[Link](j-1);
for (int i=1;i<=m;i++) for (int j=1;j<=n;j++)
dp[i][j]=(dp[i-1][j]&&[Link](i-1)==[Link](i+j-1))||
(dp[i][j-1]&&[Link](j-1)==[Link](i+j-1));
return dp[m][n];
}
}
Distinct Subsequences
Difficulty: Hard
class Solution {
public int numDistinct(String s, String t) {
int m=[Link](), n=[Link]();
int[][] dp=new int[m+1][n+1];
for (int i=0;i<=m;i++) dp[i][0]=1;
for (int i=1;i<=m;i++) for (int j=1;j<=n;j++) {
dp[i][j]=dp[i-1][j];
if ([Link](i-1)==[Link](j-1)) dp[i][j]+=dp[i-1][j-1];
}
return dp[m][n];
}
}
Edit Distance
Difficulty: Medium
class Solution {
public int minDistance(String word1, String word2) {
int m=[Link](), n=[Link]();
int[][] dp=new int[m+1][n+1];
for (int i=0;i<=m;i++) dp[i][0]=i;
for (int j=0;j<=n;j++) dp[0][j]=j;
for (int i=1;i<=m;i++) for (int j=1;j<=n;j++) {
if ([Link](i-1)==[Link](j-1)) dp[i][j]=dp[i-1][j-1];
else dp[i][j]=1+[Link](dp[i-1][j-1],[Link](dp[i-1][j],dp[i][j-1]));
}
return dp[m][n];
}
}
Burst Balloons
Difficulty: Hard
class Solution {
public int maxCoins(int[] nums) {
int n=[Link];
int[] arr=new int[n+2]; arr[0]=arr[n+1]=1;
for (int i=0;i<n;i++) arr[i+1]=nums[i];
int N=n+2;
int[][] dp=new int[N][N];
for (int len=2;len<N;len++) for (int l=0;l<N-len;l++) {
int r=l+len;
for (int k=l+1;k<r;k++)
dp[l][r]=[Link](dp[l][r],dp[l][k]+dp[k][r]+arr[l]*arr[k]*arr[r]);
}
return dp[0][N-1];
}
}
Greedy
Maximum Subarray
Difficulty: Medium
class Solution {
public int maxSubArray(int[] nums) {
int maxSum=nums[0], curSum=nums[0];
for (int i=1;i<[Link];i++) {
curSum=[Link](nums[i], curSum+nums[i]);
maxSum=[Link](maxSum,curSum);
}
return maxSum;
}
}
Jump Game
Difficulty: Medium
class Solution {
public boolean canJump(int[] nums) {
int maxReach=0;
for (int i=0;i<[Link];i++) {
if (i>maxReach) return false;
maxReach=[Link](maxReach,i+nums[i]);
}
return true;
}
}
Jump Game II
Difficulty: Medium
class Solution {
public int jump(int[] nums) {
int jumps=0, curEnd=0, farthest=0;
for (int i=0;i<[Link]-1;i++) {
farthest=[Link](farthest,i+nums[i]);
if (i==curEnd) { jumps++; curEnd=farthest; }
}
return jumps;
}
}
Gas Station
Difficulty: Medium
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int total=0, tank=0, start=0;
for (int i=0;i<[Link];i++) {
total+=gas[i]-cost[i]; tank+=gas[i]-cost[i];
if (tank<0) { start=i+1; tank=0; }
}
return total>=0?start:-1;
}
}
Hand of Straights
Difficulty: Medium
class Solution {
public boolean isNStraightHand(int[] hand, int groupSize) {
if ([Link]%groupSize!=0) return false;
TreeMap<Integer,Integer> map=new TreeMap<>();
for (int h:hand) [Link](h,1,Integer::sum);
while (![Link]()) {
int first=[Link]();
for (int i=0;i<groupSize;i++) {
if () return false;
int cnt=[Link](first+i);
if (cnt==1) [Link](first+i);
else [Link](first+i,cnt-1);
}
}
return true;
}
}
Partition Labels
Difficulty: Medium
class Solution {
public List<Integer> partitionLabels(String s) {
int[] last=new int[26];
for (int i=0;i<[Link]();i++) last[[Link](i)-'a']=i;
List<Integer> res=new ArrayList<>();
int start=0, end=0;
for (int i=0;i<[Link]();i++) {
end=[Link](end,last[[Link](i)-'a']);
if (i==end) { [Link](end-start+1); start=i+1; }
}
return res;
}
}
Valid Parenthesis String
Difficulty: Medium
class Solution {
public boolean checkValidString(String s) {
int low=0, high=0;
for (char c:[Link]()) {
if (c=='(') { low++; high++; }
else if (c==')') { low--; high--; }
else { low--; high++; }
if (high<0) return false;
low=[Link](low,0);
}
return low==0;
}
}
Intervals
Insert Interval
Difficulty: Medium
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> res=new ArrayList<>();
int i=0, n=[Link];
while (i<n&&intervals[i][1]<newInterval[0]) [Link](intervals[i++]);
while (i<n&&intervals[i][0]<=newInterval[1]) {
newInterval[0]=[Link](newInterval[0],intervals[i][0]);
newInterval[1]=[Link](newInterval[1],intervals[i++][1]);
}
[Link](newInterval);
while (i<n) [Link](intervals[i++]);
return [Link](new int[0][]);
}
}
Merge Intervals
Difficulty: Medium
class Solution {
public int[][] merge(int[][] intervals) {
[Link](intervals,(a,b)->a[0]-b[0]);
List<int[]> res=new ArrayList<>();
for (int[] cur:intervals) {
if ([Link]()||[Link]([Link]()-1)[1]<cur[0]) [Link](cur);
else [Link]([Link]()-1)[1]=[Link]([Link]([Link]()-1)[1],cur[1]);
}
return [Link](new int[0][]);
}
}
Non-overlapping Intervals
Difficulty: Medium
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
[Link](intervals,(a,b)->a[1]-b[1]);
int count=0, prevEnd=Integer.MIN_VALUE;
for (int[] in:intervals) {
if (in[0]>=prevEnd) prevEnd=in[1];
else count++;
}
return count;
}
}
Meeting Rooms
Difficulty: Easy
class Solution {
public boolean canAttendMeetings(int[][] intervals) {
[Link](intervals,(a,b)->a[0]-b[0]);
for (int i=1;i<[Link];i++)
if (intervals[i][0]<intervals[i-1][1]) return false;
return true;
}
}
Meeting Rooms II
Difficulty: Medium
class Solution {
public int minMeetingRooms(int[][] intervals) {
[Link](intervals,(a,b)->a[0]-b[0]);
PriorityQueue<Integer> pq=new PriorityQueue<>();
for (int[] iv:intervals) {
if (![Link]()&&[Link]()<=iv[0]) [Link]();
[Link](iv[1]);
}
return [Link]();
}
}
Spiral Matrix
Difficulty: Medium
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res=new ArrayList<>();
int top=0,bot=[Link]-1,left=0,right=matrix[0].length-1;
while (top<=bot&&left<=right) {
for (int c=left;c<=right;c++) [Link](matrix[top][c]); top++;
for (int r=top;r<=bot;r++) [Link](matrix[r][right]); right--;
if (top<=bot) { for (int c=right;c>=left;c--) [Link](matrix[bot][c]); bot--; }
if (left<=right) { for (int r=bot;r>=top;r--) [Link](matrix[r][left]); left++; }
}
return res;
}
}
Happy Number
Difficulty: Easy
class Solution {
public boolean isHappy(int n) {
Set<Integer> seen=new HashSet<>();
while (n!=1) {
if () return false;
int next=0;
while (n>0) { int d=n%10; next+=d*d; n/=10; }
n=next;
}
return true;
}
}
Plus One
Difficulty: Easy
class Solution {
public int[] plusOne(int[] digits) {
for (int i=[Link]-1;i>=0;i--) {
if (digits[i]<9) { digits[i]++; return digits; }
digits[i]=0;
}
int[] res=new int[[Link]+1]; res[0]=1;
return res;
}
}
Pow(x, n)
Difficulty: Medium
class Solution {
public double myPow(double x, int n) {
long N=n;
if (N<0) { x=1/x; N=-N; }
double res=1;
while (N>0) {
if ((N&1)==1) res*=x;
x*=x; N>>=1;
}
return res;
}
}
Multiply Strings
Difficulty: Medium
class Solution {
public String multiply(String num1, String num2) {
int m=[Link](), n=[Link]();
int[] pos=new int[m+n];
for (int i=m-1;i>=0;i--) for (int j=n-1;j>=0;j--) {
int mul=([Link](i)-'0')*([Link](j)-'0');
int p1=i+j, p2=i+j+1, sum=mul+pos[p2];
pos[p2]=sum%10; pos[p1]+=sum/10;
}
StringBuilder sb=new StringBuilder();
for (int p:pos) if (!([Link]()==0&&p==0)) [Link](p);
return [Link]()==0?"0":[Link]();
}
}
Detect Squares
Difficulty: Medium
class DetectSquares {
Map<String,Integer> pointCnt=new HashMap<>();
Map<Integer,Set<Integer>> xMap=new HashMap<>();
public void add(int[] point) {
String key=point[0]+","+point[1];
[Link](key,1,Integer::sum);
[Link](point[0],k->new HashSet<>()).add(point[1]);
}
public int count(int[] point) {
int ans=0, px=point[0], py=point[1];
if () return 0;
for (int y:[Link](px)) {
if (y==py) continue;
int d=y-py;
ans+=get(px+d,py)*get(px+d,y)*get(px,y);
ans+=get(px-d,py)*get(px-d,y)*get(px,y);
}
return ans;
}
int get(int x,int y) { return [Link](x+","+y,0); }
}
Bit Manipulation
Single Number
Difficulty: Easy
class Solution {
public int singleNumber(int[] nums) {
int res=0;
for (int n:nums) res^=n;
return res;
}
}
Number of 1 Bits
Difficulty: Easy
class Solution {
public int hammingWeight(int n) {
int count=0;
while (n!=0) { n&=(n-1); count++; }
return count;
}
}
Counting Bits
Difficulty: Easy
class Solution {
public int[] countBits(int n) {
int[] dp=new int[n+1];
for (int i=1;i<=n;i++) dp[i]=dp[i>>1]+(i&1);
return dp;
}
}
Reverse Bits
Difficulty: Easy
class Solution {
public int reverseBits(int n) {
int res=0;
for (int i=0;i<32;i++) { res=(res<<1)|(n&1); n>>=1; }
return res;
}
}
Missing Number
Difficulty: Easy
class Solution {
public int missingNumber(int[] nums) {
int n=[Link], expected=n*(n+1)/2, actual=0;
for (int num:nums) actual+=num;
return expected-actual;
}
}
Reverse Integer
Difficulty: Medium
class Solution {
public int reverse(int x) {
long res=0;
while (x!=0) { res=res*10+x%10; x/=10; }
return (res>Integer.MAX_VALUE||res<Integer.MIN_VALUE)?0:(int)res;
}
}