FRAZ DSA Sheet Solutions by Prashant
FRAZ DSA Sheet Solutions by Prashant
FRAZ DSA Sheet Solutions by Prashant
1. https://leetcode.com/problems/valid-parentheses/
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
class Solution {
public int maxSubArray(int[] nums) {
int maxSum = Integer.MIN_VALUE;
int maxCurrent = 0;
if (maxCurrent < 0) {
maxCurrent = 0;
}
}
return maxSum;
}
}
3. https://leetcode.com/problems/search-a-2d-matrix/
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int i = 0;
int j = matrix[0].length - 1;
return true;
} else if (target < matrix[i][j]) {
j--;
} else {
i++;
}
}
return false;
}
}
4. https://leetcode.com/problems/permutations/
class Solution {
public List < List < Integer >> permute(int[] nums) {
List < List < Integer >> result = new ArrayList < List < Integer >> ();
List < Integer > output = new ArrayList < Integer > ();
private void getCombinations(int[] nums, List < Integer > output, List < List < Integer >> result) {
if (output.size() == nums.length) {
result.add(new ArrayList < Integer > (output));
} else {
for (int i = 0; i < nums.length; i++) {
if (output.contains(nums[i])) continue;
output.add(nums[i]);
getCombinations(nums, output, result);
output.remove(output.size() - 1);
}
}
}
5. https://leetcode.com/problems/search-in-rotated-sorted-array/
class Solution {
public int search(int[] nums, int target) {
class Solution {
public ListNode reverseList(ListNode head) {
ListNode current = head;
ListNode prev = null;
while (current != null) {
}
return prev;
}
}
7. https://leetcode.com/problems/top-k-frequent-elements/
class Solution {
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> hm = new HashMap<>();
for (int e: nums)
hm.put(e, hm.getOrDefault(e, 0) + 1);
PriorityQueue<Value> pq = new PriorityQueue();
for (Integer key: hm.keySet()) {
if (pq.size()<k) pq.add(new Value(key, hm.get(key)));
else {
while (pq.size() >= k && pq.peek().freq<hm.get(key)) {
pq.poll();
}
if (pq.size()<k) pq.add(new Value(key, hm.get(key)));
}
}
int ans[] = new int[k];
int i = 0;
for (Value v: pq) {
ans[i++] = v.val;
}
return ans;
}
}
@Override
public int compareTo(Value v2) {
if (this.freq > v2.freq) return 1;
else if (this.freq<v2.freq) return -1;
else return this.freq - v2.freq;
}
@Override
public String toString() {
return "{val: " + this.val + ", freq: " + this.freq + "}";
}
}
8. https://leetcode.com/problems/decode-string/
class Solution {
public String decodeString(String s) {
int n = s.length();
Stack<Integer> numStack = new Stack<>();
Stack<Integer> indexStack = new Stack<>();
Stack<StringBuilder> strStack = new Stack<>();
while (!numStack.isEmpty()) {
int index = indexStack.pop();
int num = numStack.pop();
StringBuilder str = strStack.pop();
int l = 0;
while (j < n
&& s.charAt(j) >= '0'
&& s.charAt(j) <= '9'
){
l = l * 10 + (s.charAt(j) - '0');
j++;
}
j++;
numStack.push(l);
indexStack.push(j);
strStack.push(new StringBuilder());
break;
}
else {
str.append(c);
}
}
}
}
return res.toString();
}
}
9. https://leetcode.com/problems/reorganize-string/
class Solution {
public String reorganizeString(String s) {
result += firstPair.c;
result += secondPair.c;
firstPair.freq--;
secondPair.freq--;
if (firstPair.freq > 0) {
pq.add(firstPair);
}
if (secondPair.freq > 0) {
pq.add(secondPair);
}
}
if (pq.size() >= 1) {
result += pq.poll().c;
}
if (result.length() != s.length())
return "";
return result;
}
char c;
int freq;
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
HashMap<Integer, Integer> inorder_map = populate_map(inorder);
int[] pre_index = { 0 };
return construct_tree(preorder, inorder_map, 0, inorder.length - 1, pre_index);
class Solution {
class Solution {
public String minWindow(String s, String t) {
if (t.length() > s.length()) return "";
int m = t.length();
int n = s.length();
int[] freq = new int[58];
int[] count = new int[58];
String S = "";
int window = n + 1;
for (int i = 0; i<m; i++) {
freq[t.charAt(i) - 'A']++;
}
int l = 0;
for (int r = 0; r<n; r++) {
count[s.charAt(r) - 'A']++;
while (compare(count, freq)) {
if (r - l + 1<window) {
S = s.substring(l, r + 1);
window = r - l + 1;
}
count[s.charAt(l) - 'A']--;
l++;
}
}
return S;
}
public boolean compare(int[] count, int[] freq) {
for (int i = 0; i<freq.length; i++) {
if (count[i]<freq[i]) return false;
}
return true;
}
}
13. https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
int[] dp1 = dpIncreasing(prices);
int[] dp2 = dpDecreasing(prices);
for (int i = 1; i<prices.length; i++) {
int l1 = dp1[i];
int l2 = dp2[i];
maxProfit = Math.max(maxProfit, l1 + l2);
}
return maxProfit;
}
class Solution {
private static final int[] INT_NUMBERS = {
1 _000_000_000, 1 _000_000, 1000, 100, 90, 80, 70, 60, 50, 40, 30, 20, 19, 18, 17, 16,
15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
};
private static final String[] STRING_NUMBERS = {
"Billion", "Million", "Thousand", "Hundred", "Ninety", "Eighty", "Seventy", "Sixty",
"Fifty", "Forty", "Thirty", "Twenty",
"Nineteen", "Eighteen", "Seventeen", "Sixteen", "Fifteen", "Fourteen", "Thirteen",
"Twelve", "Eleven", "Ten",
"Nine", "Eight", "Seven", "Six", "Five", "Four", "Three", "Two", "One"
};
sb.append(STRING_NUMBERS[i]).append("
").append(numberToWordsHelper(num % INT_NUMBERS[i]));
break;
}
}
return sb.charAt(sb.length() - 1) == ' ' ? sb.deleteCharAt(sb.length() - 1) : sb; // trim
}
}
15. https://leetcode.com/problems/concatenated-words/
class Solution {
public List<String> findAllConcatenatedWordsInADict(String[] words) {
Set<String> allWords = new HashSet<>();
for(String word: words) allWords.add(word);
class Solution {
public int[] twoSum(int[] nums, int target) {
return res;
}
}
17. https://leetcode.com/problems/majority-element/
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return -1;
}
}
18. https://leetcode.com/problems/spiral-matrix/
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if (dir == 0) {
for (int i = L; i<= R; i++)
result.add(matrix[T][i]);
T++;
dir = 1;
} else if (dir == 1) {
for (int i = T; i<= B; i++)
result.add(matrix[i][R]);
R--;
dir = 2;
} else if (dir == 2) {
for (int i = R; i >= L; i--)
result.add(matrix[B][i]);
B--;
dir = 3;
} else if (dir == 3) {
for (int i = B; i >= T; i--)
result.add(matrix[i][L]);
L++;
dir = 0;
}
}
}
}
19. https://leetcode.com/problems/product-of-array-except-self/
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] res = new int[n];
res[0] = 1;
for (int i = 1; i < n; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = n - 1; i >= 0; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}
}
20. https://leetcode.com/problems/word-search/
class Solution {
public boolean exist(char[][] board, String word) {
int []flag=new int[1];
int [][]vis=new int[board.length][board[0].length];
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j]==word.charAt(0)){
check(i,j,board,word,0,flag,vis);
}
}
}
if(flag[0]==1){
return true;
}else{
return false;
}
}
public void check(int sr,int sc,char[][] board,String word,int idx,int []flag,int [][]vis){
if(idx==word.length()){
flag[0]=1;
return;
}
if(sr<0||sc<0||sr>=board.length||sc>=board[0].length||vis[sr][sc]==1||board[sr][sc]!=word.charAt
(idx)){
return;
}
vis[sr][sc]=1;
check(sr+1,sc,board,word,idx+1,flag,vis);
check(sr,sc+1,board,word,idx+1,flag,vis);
check(sr-1,sc,board,word,idx+1,flag,vis);
check(sr,sc-1,board,word,idx+1,flag,vis);
vis[sr][sc]=0;
}
}
21. https://leetcode.com/problems/find-the-duplicate-number/
class Solution {
public int findDuplicate(int[] nums) {
int slow = 0;
int fast = 0;
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
slow = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
}
22. https://leetcode.com/problems/k-diff-pairs-in-an-array/
class Solution {
public int findDuplicate(int[] nums) {
int slow = 0;
int fast = 0;
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
slow = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
}
23. https://leetcode.com/problems/subarray-sums-divisible-by-k/
class Solution {
public int subarraysDivByK(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<>();
int sum = 0;
int temp;
int res = 0;
map.put(0, 1);
for (int i = 0; i<nums.length; i++) {
sum += nums[i];
temp = sum % k;
if (temp<0) temp += k;
if (map.containsKey(temp)) {
res += map.get(temp);
}
map.put(temp, map.getOrDefault(temp, 0) + 1);
}
return res;
}
}
24. https://leetcode.com/problems/first-missing-positive/
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
if (n == 1 && nums[0] == 1) {
return 2;
} else if (n == 1 && nums[0]<0) {
return 1;
}
if (set.size() == 0) {
return 1;
}
int missnum = 0;
for (int i = 1; i<= nums.length + 1; i++) {
if (!set.contains(i)) {
missnum = i;
break;
}
}
return missnum;
}
}
25. https://leetcode.com/problems/max-value-of-equation/
class Solution {
public int findMaxValueOfEquation(int[][] points, int k) {
int max = Integer.MIN_VALUE;
int ans = 0;
int mod = 0;
int flag = 1;
for (int i = 0; i<points.length - 1; i++) {
if (flag<i + 1)
flag = i + 1;
for (int j = flag; j<points.length; j++) {
mod = points[i][0] - points[j][0];
if (mod<0)
mod = -mod;
if (mod > k)
break; // x coordinate are sorted
ans = points[i][1] + points[j][1] + mod;
if (max<ans) {
max = ans;
flag = j - 1;
}
}
}
return max;
}
}
26. https://leetcode.com/problems/word-break/
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] f = new boolean[s.length() + 1];
f[0] = true;
for(int i=1; i <= s.length(); i++){
for(int j=0; j < i; j++){
if(f[j] && wordDict.contains(s.substring(j, i))){
f[i] = true;
break;
}
}
}
return f[s.length()];
}
}
27. https://leetcode.com/problems/knight-dialer/
class Solution {
public int knightDialer(int n) {
var dp = new long[10];
var tmp = new long[10];
Arrays.fill(dp, 1);
for (int i = 1; i<n; i++) {
tmp[1] = dp[6] + dp[8];
tmp[2] = dp[7] + dp[9];
tmp[3] = dp[4] + dp[8];
tmp[4] = dp[0] + dp[3] + dp[9];
tmp[5] = 0;
tmp[6] = dp[0] + dp[1] + dp[7];
tmp[7] = dp[2] + dp[6];
tmp[8] = dp[1] + dp[3];
tmp[9] = dp[2] + dp[4];
tmp[0] = dp[4] + dp[6];
for (int j = 0; j<10; j++) tmp[j] = tmp[j] % 1000000007;
var arr = dp;
dp = tmp;
tmp = arr;
}
long res = 0;
for (int i = 0; i<10; i++) {
res = (res + dp[i]) % 1000000007;
}
return (int) res;
}
}
28. https://leetcode.com/problems/unique-paths/
class Solution {
public int uniquePaths(int m, int n) {
return dp[m-1][n-1];
}
}
29. https://leetcode.com/problems/longest-arithmetic-subsequence/
class Solution {
public int longestArithSeqLength(int[] nums) {
int[][] dp = new int[nums.length][1001];
for (int i = 0; i<nums.length; i++) Arrays.fill(dp[i], 1);
int offset = 500;
int maxAns = 0;
for (int i = 1; i<nums.length; i++) {
for (int j = 0; j<i; j++) {
int diff = nums[j] - nums[i];
int offseted = diff + offset;
dp[i][offseted] = Math.max(dp[i][offseted], dp[j][offseted] + 1);
maxAns = Math.max(maxAns, dp[i][offseted]);
}
}
return maxAns;
}
}
30. https://leetcode.com/problems/regular-expression-matching/
class Solution {
public boolean isMatch(String s, String p) {
Boolean[][] memo = new Boolean[s.length() + 1][p.length() + 1];
return find(s, p, 0, 0, memo);
}
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
stack.push(-1);
int res = 0;
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(c==')' && stack.peek()!=-1 && s.charAt(stack.peek())=='('){
stack.pop();
res = Math.max(res, i-stack.peek());
}else{
stack.push(i);
}
}
return res;
}
}
32. https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/
class Solution {
public int minDifficulty(int[] jobDifficulty, int d) {
if (jobDifficulty.length<d) return -1;
int[][] dp = new int[jobDifficulty.length][d];
int[][] rangeMax = getRangeMax(jobDifficulty);
for (int i = 0; i<jobDifficulty.length; i++) dp[i][0] = rangeMax[0][i];
for (int cut = 1; cut<d; cut++) {
for (int i = cut; i<jobDifficulty.length; i++) {
dp[i][cut] = Integer.MAX_VALUE;
for (int j = cut - 1; j<i; j++) {
dp[i][cut] = Math.min(dp[i][cut], dp[j][cut - 1] + rangeMax[j
+ 1][i]);
}
}
}
return dp[jobDifficulty.length - 1][d - 1];
}
}
33. https://leetcode.com/problems/minimum-cost-to-cut-a-stick/
class Solution {
public int minCost(int n, int[] cuts) {
int c = cuts.length;
class Solution {
public int strStr(String haystack, String needle) {
haystack = haystack.replaceAll(needle, "-");
for (int i = 0; i<haystack.length(); i++) {
if (haystack.charAt(i) == '-')
return i;
}
return -1;
}
}
35. https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
class Solution {
public String minRemoveToMakeValid(String s) {
StringBuilder sb = new StringBuilder(s);
Stack<Integer> st = new Stack<>();
for (int i = 0; i<sb.length(); ++i) {
if (sb.charAt(i) == '(') st.add(i);
if (sb.charAt(i) == ')') {
if (!st.empty()) st.pop();
else sb.setCharAt(i, '*');
}
}
while (!st.empty())
sb.setCharAt(st.pop(), '*');
return sb.toString().replaceAll("\\*", "");
}
}
36. https://leetcode.com/problems/basic-calculator-ii/
class Solution {
public int calculate(String s) {
if (s == null || s.length() == 0) return 0;
int curr = 0;
char op = '+';
char[] ch = s.toCharArray();
int sum = 0;
int last = 0;
for (int i = 0; i<ch.length; i++) {
if (Character.isDigit(ch[i])) {
curr = curr * 10 + ch[i] - '0';
}
if (!Character.isDigit(ch[i]) && ch[i] != ' ' || i == ch.length - 1) {
if (op == '+') {
sum += last;
last = curr;
} else if (op == '-') {
sum += last;
last = -curr;
} else if (op == '*') {
last = last * curr;
} else if (op == '/') {
last = last / curr;
}
op = ch[i];
curr = 0;
}
}
sum += last;
return sum;
}
}
37. https://leetcode.com/problems/power-of-two/
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n == 1 || (n%2 == 0 && isPowerOfTwo(n/2)));
}
}
38. https://leetcode.com/problems/string-to-integer-atoi/
class Solution {
public int myAtoi(String s) {
if (s == null || s.isEmpty() || s.length() > 200) return 0;
if (currentIndex<length) {
if (s.charAt(currentIndex) == '-') {
signDriver *= -1;
currentIndex++;
} else if (s.charAt(currentIndex) == '+') {
currentIndex++;
}
}
class Solution {
public int maxPoints(int[][] points) {
int max = 0;
for(int i = 0; i < points.length; ++i){
int vertical = 0;
int horizontal = 0;
HashMap<Double,Integer> map = new HashMap();
for(int j = 0; j<points.length; ++j){
if(i != j){
if(points[i][0] == points[j][0]){
vertical++;
max = Math.max(vertical,max);
}
else if(points[i][1] == points[j][1]){
horizontal++;
max = Math.max(horizontal,max);
}
else{
double gradient = (points[i][1] - points[j][1])*1.00/(points[i][0] - points[j][0]);
max = Math.max(max,map.getOrDefault(gradient,0)+1);
map.put(gradient,map.getOrDefault(gradient,0)+1);}
}
}
}
return max + 1;
}
}
40. https://leetcode.com/problems/remove-k-digits/
class Solution {
public String removeKdigits(String num, int k) {
Stack<Integer> stack = new Stack<>();
class Solution {
}
42. https://leetcode.com/problems/house-robber-iii/
class Solution {
public int rob(TreeNode root) {
Map<TreeNode, Integer> map = new HashMap<>();
return helper(root, map);
}
int helper(TreeNode root, Map<TreeNode, Integer> map) {
if (root == null)
return 0;
if (map.get(root) != null)
return map.get(root);
int taken = root.val;
if (root.left != null) {
taken += helper(root.left.left, map);
taken += helper(root.left.right, map);
}
if (root.right != null) {
taken += helper(root.right.left, map);
taken += helper(root.right.right, map);
}
int notTaken = 0;
notTaken += helper(root.left, map);
notTaken += helper(root.right, map);
int ans = Math.max(taken, notTaken);
map.put(root, ans);
return ans;
}
}
43. https://leetcode.com/problems/critical-connections-in-a-network/
class Solution {
public void dfs(int node, ArrayList<ArrayList<Integer>> graph, int timer, int parent,
boolean[] vis, int[] tin, int[] low, List<List<Integer>> critical_connections) {
vis[node] = true;
tin[node] = low[node] = ++timer;
Iterator<Integer> itr = graph.get(node).listIterator();
while (itr.hasNext()) {
int neigh = itr.next();
if (neigh == parent) continue;
if (!vis[neigh]) {
dfs(neigh, graph, timer, node, vis, tin, low, critical_connections);
low[node] = Math.min(low[node], low[neigh]);
if (low[neigh] > tin[node]) {
ArrayList<Integer> connection = new ArrayList<>();
connection.add(node);
connection.add(neigh);
critical_connections.add(connection);
}
} else {
low[node] = Math.min(low[node], tin[neigh]);
}
}
}
public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for (int i = 0; i<n; i++) graph.add(new ArrayList<Integer> ());
for (List<Integer> edge: connections) {
int u = edge.get(0), v = edge.get(1);
graph.get(u).add(v);
graph.get(v).add(u);
}
List<List<Integer>> critical_connections = new ArrayList<>();
boolean[] vis = new boolean[n];
int[] tin = new int[n];
int[] low = new int[n];
int parent = -1;
int timer = 0;
class Solution {
int max = 0;
public int heightTree(TreeNode root) {
if (root == null)
return 0;
int lh = (heightTree(root.left));
int rh = (heightTree(root.right));
max = Math.max(max, lh + rh);
return 1 + Math.max(lh, rh);
}
public int diameterOfBinaryTree(TreeNode root) {
heightTree(root);
return max;
}
}
45. https://leetcode.com/problems/redundant-connection/
class DSU {
int[] parent;
int[] rank;
DSU(int n) {
parent = new int[n];
Arrays.fill(parent, -1);
rank = new int[n];
Arrays.fill(rank, 1);
}
class UnionFind {
int[] parents;
int[] ranks;
UnionFind(int n) {
parents = new int[n];
ranks = new int[n];
Arrays.fill(ranks, 1);
for (int i = 0; i<n; i++)
parents[i] = i;
}
public int find(int v) {
if (parents[v] == v)
return v;
return find(parents[v]);
}
public boolean union(int v1, int v2) {
int ar1 = find(v1);
int ar2 = find(v2);
if (ar1 == ar2)
return false;
if (ranks[ar1] > ranks[ar2])
parents[ar2] = ar1;
else if (ranks[ar2] > ranks[ar1])
parents[ar1] = ar2;
else {
parents[ar1] = ar2;
ranks[ar2]++;
}
return true;
}
}
class Solution {
public int[] findRedundantDirectedConnection(int[][] edges) {
Integer nodeWith2Indegree = getIndegreeTwo(edges);
UnionFind uf = new UnionFind(edges.length + 1);
if (nodeWith2Indegree == null) {
for (int[] edge: edges) {
if (!uf.union(edge[0], edge[1]))
return edge;
}
} else {
int[][] twoEdges = new int[2][2];
int top = -1;
for (int[] edge: edges) {
if (edge[1] == nodeWith2Indegree)
twoEdges[++top] = edge;
if (top == 1)
break;
}
if (hasCycle(uf, edges, twoEdges[1]))
return twoEdges[0];
else
return twoEdges[1];
}
return null;
}
private boolean hasCycle(UnionFind uf, int[][] edges, int[] skipEdge) {
for (int[] edge: edges) {
if (edge != skipEdge)
if (!uf.union(edge[0], edge[1]))
return true;
}
return false;
}
private Integer getIndegreeTwo(int[][] edges) {
int[] map = new int[edges.length + 1];
for (int[] edge: edges)
if (++map[edge[1]] == 2)
return edge[1];
return null;
}
}
47. https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/
class Solution {
public int shipWithinDays(int[] weights, int days) {
int n = weights.length;
int ans = 0;
int max = 0;
int sum = 0;
if (n == days) {
return max;
}
int l = max;
int h = sum;
while (l<= h) {
int mid = l + (h - l) / 2;
if (isPossible(weights, mid, days) == true) {
ans = mid;
h = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
class Solution {
public int orangesRotting(int[][] grid) {
if(grid == null || grid.length == 0) return 0;
int rows = grid.length;
int cols = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
int count_fresh = 0;
class Solution {
public int characterReplacement(String s, int k) {
if (k == s.length() || k - 1 == s.length()) {
return s.length();
}
class LRUCache {
if (map.containsKey(key)) {
Node node = map.get(key);
remove(node);
insert(node);
return node.value;
} else {
return -1;
}
node.prev = head;
head.next = node;
node.next = headNext;
headNext.prev = node;
}
node.prev.next = node.next;
node.next.prev = node.prev;
}
if (map.containsKey(key)) {
remove(map.get(key));
}
if (map.size() == capacity) {
remove(tail.prev);
}
class Node {
Node prev, next;
int key, value;
}
}