├── 10Jan.java ├── 10feb.java ├── 11feb.java ├── 11thJan.java ├── 12Jan.java ├── 12feb.java ├── 13feb.java ├── 13thJan.java ├── 14Jan.java ├── 14feb.java ├── 15Jan.java ├── 15jan.java ├── 16Jan.java ├── 16feb.java ├── 17feb.java ├── 17jan.java ├── 18Jan.java ├── 19feb.java ├── 19jan.java ├── 1feb.java ├── 1mar.java ├── 1stJan.java ├── 20feb.java ├── 20jan.java ├── 21feb.java ├── 21jan.java ├── 22feb.java ├── 22jan.java ├── 23feb.java ├── 23jan.java ├── 24feb.java ├── 24jan.java ├── 25Jan.java ├── 25feb.java ├── 25jan.java ├── 26feb.java ├── 26jan.java ├── 27jan.java ├── 28feb.java ├── 28jan.java ├── 29jan.java ├── 2feb.java ├── 2mar.java ├── 2ndJan.java ├── 30jan.java ├── 31jan.java ├── 3feb.java ├── 3mar.java ├── 3rdJan.java ├── 4feb.java ├── 4mar.java ├── 4thJan.java ├── 5feb.java ├── 5thJan.java ├── 6jan.java ├── 6thJan.java ├── 7feb.java ├── 7thJan.java ├── 8Jan.java ├── 8feb.java ├── 9feb.java ├── 9thJan.java ├── April ├── 11apr.java ├── 12apr.java ├── 13apr.java ├── 15apr.java ├── 16apr.java ├── 17apr.java ├── 18apr.java ├── 19apr.java ├── 1apr.java ├── 2apr.java ├── 3apr.java ├── 4apr.java ├── 5apr.java ├── 6apr.java ├── 7apr.java └── 8apr.java ├── Contests ├── 4ma.java ├── 4mar.java ├── 4marc.java └── 4march.java ├── Day24.c++ ├── Make the array beautiful - GFG ├── README.md └── make-the-array-beautiful.cpp ├── March ├── 10mar.java ├── 11mar.java ├── 12mar.java ├── 13mar.java ├── 14mar.java ├── 15mar.java ├── 16mar.java ├── 17mar.java ├── 18mar.java ├── 19mar.java ├── 20mar.java ├── 21mar.java ├── 22mar.java ├── 23mar.java ├── 24mar.java ├── 25mar.java ├── 26mar.java ├── 27mar.java ├── 28mar.java ├── 29mar.java ├── 30mar.java ├── 31mar.java ├── 5mar.java ├── 6mar.java ├── 7mar.java ├── 8mar.java └── 9mar.java ├── Pattern - GFG ├── README.md └── pattern.cpp ├── Pattern 1 - GFG ├── README.md └── pattern-1.cpp ├── Pattern 11 - GFG ├── README.md └── pattern-11.cpp ├── Pattern 12 - GFG ├── README.md └── pattern-12.cpp ├── Pattern 13 - GFG ├── README.md └── pattern-13.cpp ├── Pattern 14 - GFG └── pattern-14.cpp ├── Pattern 15 - GFG ├── README.md └── pattern-15.cpp ├── Pattern 16 - GFG ├── README.md └── pattern-16.cpp ├── Pattern 17 - GFG ├── README.md └── pattern-17.cpp ├── Pattern 2 - GFG ├── README.md └── pattern-2.cpp ├── Pattern 3 - GFG ├── README.md └── pattern-3.cpp ├── Pattern 4 - GFG ├── README.md └── pattern-4.cpp ├── Pattern 5 - GFG ├── README.md └── pattern-5.cpp ├── Pattern 6 - GFG ├── README.md └── pattern-6.cpp ├── Pattern 7 - GFG ├── README.md └── pattern-7.cpp ├── Pattern 8 - GFG ├── README.md └── pattern-8.cpp ├── README.md ├── Study plans └── leetcode 75 │ └── 72. Edit Distance.java ├── day1.c++ ├── day10.c++ ├── day11.c++ ├── day12.c++ ├── day13.c++ ├── day14.c++ ├── day15.c++ ├── day16.c++ ├── day17.c++ ├── day18.c++ ├── day19.c++ ├── day2.c++ ├── day20.c++ ├── day21.c++ ├── day22.c++ ├── day23.c++ ├── day25.c++ ├── day26.c++ ├── day27.c++ ├── day28.c++ ├── day3.c++ ├── day30.c++ ├── day31.c++ ├── day33.c++ ├── day34.c++ ├── day35.c++ ├── day36.c++ ├── day37.c++ ├── day38.c++ ├── day39.c++ ├── day4.c++ ├── day40.c++ ├── day41.c++ ├── day42.java ├── day43.c++ ├── day44.c++ ├── day45.c++ ├── day46.c++ ├── day47.c++ ├── day48.c++ ├── day49.c++ ├── day5.c++ ├── day50.c++ ├── day51.c++ ├── day52.c++ ├── day53.c++ ├── day54.c++ ├── day56.c++ ├── day57.c++ ├── day58.c++ ├── day6.c++ ├── day60.c++ ├── day61.c++ ├── day63.c++ ├── day65.c++ ├── day66.c++ ├── day68.c++ ├── day69.c++ ├── day7.c++ ├── day70.c++ ├── day71.c++ ├── day72.c++ ├── day73.c++ ├── day74.c++ ├── day76.c++ ├── day79.c++ ├── day8.c++ ├── day9.c++ └── may 2023 ├── 1may.java └── 2may.java /10Jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isSameTree(TreeNode p, TreeNode q) { 3 | if (p == null || q == null) 4 | return p == q; 5 | return p.val == q.val && 6 | isSameTree(p.left, q.left) && 7 | isSameTree(p.right, q.right); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /10feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxDistance(int[][] grid) { 3 | final int m = grid.length; 4 | final int n = grid[0].length; 5 | final int[] dirs = {0, 1, 0, -1, 0}; 6 | Queue> q = new ArrayDeque<>(); 7 | int water = 0; 8 | 9 | for (int i = 0; i < m; ++i) 10 | for (int j = 0; j < n; ++j) 11 | if (grid[i][j] == 0) 12 | ++water; 13 | else 14 | q.offer(new Pair<>(i, j)); 15 | 16 | if (water == 0 || water == m * n) 17 | return -1; 18 | 19 | int ans = 0; 20 | 21 | for (int d = 0; !q.isEmpty(); ++d) 22 | for (int sz = q.size(); sz > 0; --sz) { 23 | Pair pair = q.poll(); 24 | final int i = pair.getKey(); 25 | final int j = pair.getValue(); 26 | ans = d; 27 | for (int k = 0; k < 4; ++k) { 28 | final int x = i + dirs[k]; 29 | final int y = j + dirs[k + 1]; 30 | if (x < 0 || x == m || y < 0 || y == n) 31 | continue; 32 | if (grid[x][y] > 0) 33 | continue; 34 | q.offer(new Pair<>(x, y)); 35 | grid[x][y] = 2; // Mark as visited. 36 | } 37 | } 38 | 39 | return ans; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /11feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int[] shortestAlternatingPaths(int n, int[][] red, int[][] blue) { 4 | int ans[]= new int[n]; 5 | List>> list = new ArrayList<>(); 6 | for(int i=0; i> curr= new ArrayList<>(); 9 | curr.add(new ArrayList<>()); curr.add(new ArrayList<>()); 10 | list.add(curr); 11 | } 12 | for(int curr[]:red) 13 | { 14 | list.get(curr[0]).get(0).add(curr[1]); 15 | } 16 | 17 | for(int curr[]:blue) 18 | { 19 | list.get(curr[0]).get(1).add(curr[1]); 20 | } 21 | PriorityQueue pq= new PriorityQueue<>((a,b)->a[0]-b[0]); 22 | pq.add(new int[]{0, 0, 0}); 23 | Arrays.fill(ans, Integer.MAX_VALUE); 24 | boolean[][] visited= new boolean[n][2]; 25 | 26 | while(!pq.isEmpty()) 27 | { 28 | int size= pq.size(); 29 | 30 | while(size-->0) 31 | { int curr[]=pq.remove(); 32 | if(visited[curr[2]][1] && visited[curr[2]][0] ) 33 | continue; 34 | 35 | ans[curr[2]]=Math.min(curr[0], ans[curr[2]]); 36 | if(curr[2]==0) 37 | { 38 | int t=0; 39 | List list1 = list.get(curr[2]).get(t); 40 | for(int next:list1) 41 | { 42 | int nt=1; 43 | 44 | pq.add(new int[]{curr[0]+1, nt, next }); 45 | } 46 | t=1; 47 | list1 = list.get(curr[2]).get(t); 48 | for(int next:list1) 49 | { 50 | int nt=0; 51 | 52 | pq.add(new int[]{curr[0]+1, nt, next }); 53 | } 54 | visited[0][1]=true; 55 | visited[0][0]=true; 56 | } 57 | else 58 | { 59 | 60 | int t=curr[1]==1?1:0; 61 | if(visited[curr[2]][t]) continue; 62 | visited[curr[2]][t]=true; 63 | List list1 = list.get(curr[2]).get(t); 64 | for(int next:list1) 65 | { 66 | int nt=t==1?0:1; 67 | 68 | pq.add(new int[]{curr[0]+1, nt, next }); 69 | } 70 | } 71 | 72 | } 73 | } 74 | for(int i=0; i hasApple) { 3 | List[] graph = new List[n]; 4 | 5 | for (int i = 0; i < n; ++i) 6 | graph[i] = new ArrayList<>(); 7 | 8 | for (int[] edge : edges) { 9 | final int u = edge[0]; 10 | final int v = edge[1]; 11 | graph[u].add(v); 12 | graph[v].add(u); 13 | } 14 | 15 | return dfs(graph, 0, new boolean[n], hasApple); 16 | } 17 | 18 | private int dfs(List[] graph, int u, boolean[] seen, List hasApple) { 19 | seen[u] = true; 20 | int totalCost = 0; 21 | 22 | for (final int v : graph[u]) { 23 | if (seen[v]) 24 | continue; 25 | final int cost = dfs(graph, v, seen, hasApple); 26 | if (cost > 0 || hasApple.get(v)) 27 | totalCost += cost + 2; 28 | } 29 | 30 | return totalCost; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /12Jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] countSubTrees(int n, int[][] edges, String labels) { 3 | int[] ans = new int[n]; 4 | List[] graph = new List[n]; 5 | 6 | for (int i = 0; i < n; ++i) 7 | graph[i] = new ArrayList<>(); 8 | 9 | for (int[] edge : edges) { 10 | final int u = edge[0]; 11 | final int v = edge[1]; 12 | graph[u].add(v); 13 | graph[v].add(u); 14 | } 15 | 16 | dfs(graph, 0, -1, labels, ans); 17 | 18 | return ans; 19 | } 20 | 21 | private int[] dfs(List[] graph, int u, int parent, final String labels, int[] ans) { 22 | int[] count = new int[26]; // Count of letters down from this u 23 | 24 | for (final int v : graph[u]) { 25 | if (v == parent) 26 | continue; 27 | int[] childCount = dfs(graph, v, u, labels, ans); 28 | for (int i = 0; i < 26; ++i) 29 | count[i] += childCount[i]; 30 | } 31 | 32 | ans[u] = ++count[labels.charAt(u) - 'a']; // The u itself 33 | return count; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /12feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long minimumFuelCost(int[][] roads, int seats) { 3 | List[] graph = new List[roads.length + 1]; 4 | 5 | for (int i = 0; i < graph.length; ++i) 6 | graph[i] = new ArrayList<>(); 7 | 8 | for (int[] road : roads) { 9 | final int u = road[0]; 10 | final int v = road[1]; 11 | graph[u].add(v); 12 | graph[v].add(u); 13 | } 14 | 15 | dfs(graph, 0, -1, seats); 16 | return ans; 17 | } 18 | 19 | private long ans = 0; 20 | 21 | private int dfs(List[] graph, int u, int prev, int seats) { 22 | int people = 1; 23 | for (final int v : graph[u]) { 24 | if (v == prev) 25 | continue; 26 | people += dfs(graph, v, u, seats); 27 | } 28 | if (u > 0) 29 | // # of cars needed = ceil(people / seats) 30 | ans += (people + seats - 1) / seats; 31 | return people; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /13feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countOdds(int low, int high) { 3 | return (high + 1) / 2 - low / 2; 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /13thJan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestPath(int[] parent, String s) { 3 | final int n = parent.length; 4 | List[] graph = new List[n]; 5 | 6 | for (int i = 0; i < n; ++i) 7 | graph[i] = new ArrayList<>(); 8 | 9 | for (int i = 1; i < n; ++i) 10 | graph[parent[i]].add(i); 11 | 12 | longestPathDownFrom(graph, 0, s); 13 | return ans; 14 | } 15 | 16 | private int ans = 0; 17 | 18 | private int longestPathDownFrom(List[] graph, int u, final String s) { 19 | int max1 = 0; 20 | int max2 = 0; 21 | 22 | for (final int v : graph[u]) { 23 | final int res = longestPathDownFrom(graph, v, s); 24 | if (s.charAt(u) == s.charAt(v)) 25 | continue; 26 | if (res > max1) { 27 | max2 = max1; 28 | max1 = res; 29 | } else if (res > max2) { 30 | max2 = res; 31 | } 32 | } 33 | 34 | ans = Math.max(ans, 1 + max1 + max2); 35 | return 1 + max1; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /14Jan.java: -------------------------------------------------------------------------------- 1 | class UnionFind { 2 | public UnionFind(int n) { 3 | id = new int[n]; 4 | for (int i = 0; i < n; ++i) 5 | id[i] = i; 6 | } 7 | 8 | public void union(int u, int v) { 9 | final int i = find(u); 10 | final int j = find(v); 11 | if (i > j) 12 | id[i] = j; 13 | else 14 | id[j] = i; 15 | } 16 | 17 | public int find(int u) { 18 | return id[u] == u ? u : (id[u] = find(id[u])); 19 | } 20 | 21 | private int[] id; 22 | } 23 | 24 | class Solution { 25 | public String smallestEquivalentString(String s1, String s2, String baseStr) { 26 | StringBuilder sb = new StringBuilder(); 27 | UnionFind uf = new UnionFind(26); 28 | 29 | for (int i = 0; i < s1.length(); ++i) 30 | uf.union(s1.charAt(i) - 'a', s2.charAt(i) - 'a'); 31 | 32 | for (final char c : baseStr.toCharArray()) 33 | sb.append((char) ('a' + uf.find(c - 'a'))); 34 | 35 | return sb.toString(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /14feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String addBinary(String a, String b) { 3 | StringBuilder sb = new StringBuilder(); 4 | int carry = 0; 5 | int i = a.length() - 1; 6 | int j = b.length() - 1; 7 | 8 | while (i >= 0 || j >= 0 || carry == 1) { 9 | if (i >= 0) 10 | carry += a.charAt(i--) - '0'; 11 | if (j >= 0) 12 | carry += b.charAt(j--) - '0'; 13 | sb.append(carry % 2); 14 | carry /= 2; 15 | } 16 | 17 | return sb.reverse().toString(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /15Jan.java: -------------------------------------------------------------------------------- 1 | class UnionFind { 2 | public UnionFind(int n) { 3 | id = new int[n]; 4 | rank = new int[n]; 5 | for (int i = 0; i < n; ++i) 6 | id[i] = i; 7 | } 8 | 9 | public void unionByRank(int u, int v) { 10 | final int i = find(u); 11 | final int j = find(v); 12 | if (i == j) 13 | return; 14 | if (rank[i] < rank[j]) { 15 | id[i] = id[j]; 16 | } else if (rank[i] > rank[j]) { 17 | id[j] = id[i]; 18 | } else { 19 | id[i] = id[j]; 20 | ++rank[j]; 21 | } 22 | } 23 | 24 | public int find(int u) { 25 | return id[u] == u ? u : (id[u] = find(id[u])); 26 | } 27 | 28 | private int[] id; 29 | private int[] rank; 30 | } 31 | 32 | class Solution { 33 | public int numberOfGoodPaths(int[] vals, int[][] edges) { 34 | final int n = vals.length; 35 | int ans = n; 36 | UnionFind uf = new UnionFind(n); 37 | List[] graph = new List[n]; 38 | Map> valToNodes = new TreeMap<>(); 39 | 40 | for (int i = 0; i < n; ++i) 41 | graph[i] = new ArrayList<>(); 42 | 43 | for (int[] edge : edges) { 44 | final int u = edge[0]; 45 | final int v = edge[1]; 46 | if (vals[v] <= vals[u]) 47 | graph[u].add(v); 48 | if (vals[u] <= vals[v]) 49 | graph[v].add(u); 50 | } 51 | 52 | for (int i = 0; i < vals.length; ++i) { 53 | valToNodes.putIfAbsent(vals[i], new ArrayList<>()); 54 | valToNodes.get(vals[i]).add(i); 55 | } 56 | 57 | for (Map.Entry> entry : valToNodes.entrySet()) { 58 | final int val = entry.getKey(); 59 | List nodes = entry.getValue(); 60 | for (final int u : nodes) 61 | for (final int v : graph[u]) 62 | uf.unionByRank(u, v); 63 | Map rootCount = new HashMap<>(); 64 | for (final int u : nodes) 65 | rootCount.merge(uf.find(u), 1, Integer::sum); 66 | // For each group, C(count, 2) := count * (count - 1) / 2 67 | for (final int count : rootCount.values()) 68 | ans += count * (count - 1) / 2; 69 | } 70 | 71 | return ans; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /15jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List addToArrayForm(int[] num, int k) { 3 | List ans = new LinkedList<>(); 4 | 5 | for (int i = num.length - 1; i >= 0; --i) { 6 | ans.add(0, (num[i] + k) % 10); 7 | k = (num[i] + k) / 10; 8 | } 9 | 10 | while (k > 0) { 11 | ans.add(0, k % 10); 12 | k /= 10; 13 | } 14 | 15 | return ans; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /16Jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] insert(int[][] intervals, int[] newInterval) { 3 | final int n = intervals.length; 4 | List ans = new ArrayList<>(); 5 | int i = 0; 6 | 7 | while (i < n && intervals[i][1] < newInterval[0]) 8 | ans.add(intervals[i++]); 9 | 10 | while (i < n && intervals[i][0] <= newInterval[1]) { 11 | newInterval[0] = Math.min(newInterval[0], intervals[i][0]); 12 | newInterval[1] = Math.max(newInterval[1], intervals[i][1]); 13 | ++i; 14 | } 15 | 16 | ans.add(newInterval); 17 | 18 | while (i < n) 19 | ans.add(intervals[i++]); 20 | 21 | return ans.toArray(new int[ans.size()][]); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /16feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxDepth(TreeNode root) { 3 | if (root == null) 4 | return 0; 5 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /17feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minDiffInBST(TreeNode root) { 3 | inorder(root); 4 | return ans; 5 | } 6 | 7 | private int ans = Integer.MAX_VALUE; 8 | private Integer pred = null; 9 | 10 | private void inorder(TreeNode root) { 11 | if (root == null) 12 | return; 13 | 14 | inorder(root.left); 15 | if (pred != null) 16 | ans = Math.min(ans, root.val - pred); 17 | pred = root.val; 18 | inorder(root.right); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /17jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minFlipsMonoIncr(String S) { 3 | int[] dp = new int[2]; 4 | 5 | for (int i = 0; i < S.length(); ++i) { 6 | int temp = dp[0] + (S.charAt(i) == '1' ? 1 : 0); 7 | dp[1] = Math.min(dp[0], dp[1]) + (S.charAt(i) == '0' ? 1 : 0); 8 | dp[0] = temp; 9 | } 10 | 11 | return Math.min(dp[0], dp[1]); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /18Jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxSubarraySumCircular(int[] A) { 3 | int totalSum = 0; 4 | int currMaxSum = 0; 5 | int currMinSum = 0; 6 | int maxSum = Integer.MIN_VALUE; 7 | int minSum = Integer.MAX_VALUE; 8 | 9 | for (int a : A) { 10 | totalSum += a; 11 | currMaxSum = Math.max(currMaxSum + a, a); 12 | currMinSum = Math.min(currMinSum + a, a); 13 | maxSum = Math.max(maxSum, currMaxSum); 14 | minSum = Math.min(minSum, currMinSum); 15 | } 16 | 17 | return maxSum < 0 ? maxSum : Math.max(maxSum, totalSum - minSum); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /19feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> zigzagLevelOrder(TreeNode root) { 3 | if (root == null) 4 | return new ArrayList<>(); 5 | 6 | List> ans = new ArrayList<>(); 7 | Deque q = new ArrayDeque<>(Arrays.asList(root)); 8 | boolean isLeftToRight = true; 9 | 10 | while (!q.isEmpty()) { 11 | List currLevel = new ArrayList<>(); 12 | for (int sz = q.size(); sz > 0; --sz) { 13 | TreeNode node = q.poll(); 14 | if (isLeftToRight) 15 | currLevel.add(node.val); 16 | else 17 | currLevel.add(0, node.val); 18 | if (node.left != null) 19 | q.offer(node.left); 20 | if (node.right != null) 21 | q.offer(node.right); 22 | } 23 | ans.add(currLevel); 24 | isLeftToRight = !isLeftToRight; 25 | } 26 | 27 | return ans; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /19jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subarraysDivByK(int[] A, int K) { 3 | int ans = 0; 4 | int prefix = 0; 5 | int[] count = new int[K]; 6 | count[0] = 1; 7 | 8 | for (int a : A) { 9 | prefix = (prefix + a % K + K) % K; 10 | ans += count[prefix]; 11 | ++count[prefix]; 12 | } 13 | 14 | return ans; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /1feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String gcdOfStrings(String str1, String str2) { 3 | if (str1.length() < str2.length()) 4 | return gcdOfStrings(str2, str1); 5 | if (!str1.startsWith(str2)) 6 | return ""; 7 | if (str2.isEmpty()) 8 | return str1; 9 | return gcdOfStrings(str2, mod(str1, str2)); 10 | } 11 | 12 | private String mod(String s1, final String s2) { 13 | while (s1.startsWith(s2)) 14 | s1 = s1.substring(s2.length()); 15 | return s1; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /1mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] sortArray(int[] nums) { 3 | quickSort(nums, 0, nums.length - 1); 4 | return nums; 5 | } 6 | 7 | private void quickSort(int[] A, int l, int r) { 8 | if (l >= r) 9 | return; 10 | 11 | final int m = partition(A, l, r); 12 | quickSort(A, l, m - 1); 13 | quickSort(A, m + 1, r); 14 | } 15 | 16 | private int partition(int[] A, int l, int r) { 17 | final int randIndex = new Random().nextInt(r - l + 1) + l; 18 | swap(A, randIndex, r); 19 | final int pivot = A[r]; 20 | int nextSwapped = l; 21 | for (int i = l; i < r; ++i) 22 | if (A[i] <= pivot) 23 | swap(A, nextSwapped++, i); 24 | swap(A, nextSwapped, r); 25 | return nextSwapped; 26 | } 27 | 28 | private void swap(int[] A, int i, int j) { 29 | final int temp = A[i]; 30 | A[i] = A[j]; 31 | A[j] = temp; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /1stJan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean wordPattern(String pattern, String str) { 3 | String[] words = str.split(" "); 4 | if (words.length != pattern.length()) 5 | return false; 6 | 7 | Map charToIndex = new HashMap<>(); 8 | Map stringToIndex = new HashMap<>(); 9 | 10 | for (Integer i = 0; i < pattern.length(); ++i) 11 | if (charToIndex.put(pattern.charAt(i), i) != stringToIndex.put(words[i], i)) 12 | return false; 13 | 14 | return true; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /20feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int searchInsert(int[] nums, int target) { 3 | int l = 0; 4 | int r = nums.length; 5 | 6 | while (l < r) { 7 | final int m = (l + r) / 2; 8 | if (nums[m] == target) 9 | return m; 10 | if (nums[m] < target) 11 | l = m + 1; 12 | else 13 | r = m; 14 | } 15 | 16 | return l; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /20jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> findSubsequences(int[] nums) { 3 | List> ans = new LinkedList<>(); 4 | dfs(nums, 0, new LinkedList<>(), ans); 5 | return ans; 6 | } 7 | 8 | private void dfs(int[] nums, int s, LinkedList path, List> ans) { 9 | if (path.size() > 1) 10 | ans.add(new LinkedList<>(path)); 11 | 12 | Set used = new HashSet<>(); 13 | 14 | for (int i = s; i < nums.length; ++i) { 15 | if (used.contains(nums[i])) 16 | continue; 17 | if (path.isEmpty() || nums[i] >= path.getLast()) { 18 | used.add(nums[i]); 19 | path.addLast(nums[i]); 20 | dfs(nums, i + 1, path, ans); 21 | path.removeLast(); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /21feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int singleNonDuplicate(int[] nums) { 3 | int l = 0; 4 | int r = nums.length - 1; 5 | 6 | while (l < r) { 7 | int m = (l + r) / 2; 8 | if (m % 2 == 1) 9 | --m; 10 | if (nums[m] == nums[m + 1]) 11 | l = m + 2; 12 | else 13 | r = m; 14 | } 15 | 16 | return nums[l]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /21jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List restoreIpAddresses(final String s) { 3 | List ans = new ArrayList<>(); 4 | dfs(s, 0, new ArrayList<>(), ans); 5 | return ans; 6 | } 7 | 8 | private void dfs(final String s, int start, List path, List ans) { 9 | if (path.size() == 4 && start == s.length()) { 10 | ans.add(String.join(".", path)); 11 | return; 12 | } 13 | if (path.size() == 4 || start == s.length()) 14 | return; 15 | 16 | for (int length = 1; length <= 3; ++length) { 17 | if (start + length > s.length()) // Out of bound 18 | return; 19 | if (length > 1 && s.charAt(start) == '0') // Leading '0' 20 | return; 21 | final String num = s.substring(start, start + length); 22 | if (Integer.parseInt(num) > 255) 23 | return; 24 | path.add(num); 25 | dfs(s, start + length, path, ans); 26 | path.remove(path.size() - 1); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /22feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int shipWithinDays(int[] weights, int days) { 3 | int l = Arrays.stream(weights).max().getAsInt(); 4 | int r = Arrays.stream(weights).sum(); 5 | 6 | while (l < r) { 7 | final int m = (l + r) / 2; 8 | if (shipDays(weights, m) <= days) 9 | r = m; 10 | else 11 | l = m + 1; 12 | } 13 | 14 | return l; 15 | } 16 | 17 | private int shipDays(int[] weights, int shipCapacity) { 18 | int days = 1; 19 | int capacity = 0; 20 | for (final int weight : weights) { 21 | if (capacity + weight > shipCapacity) { 22 | ++days; 23 | capacity = weight; 24 | } else 25 | capacity += weight; 26 | } 27 | return days; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /22jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> partition(String s) { 3 | List> ans = new ArrayList<>(); 4 | dfs(s, 0, new ArrayList<>(), ans); 5 | return ans; 6 | } 7 | 8 | private void dfs(final String s, int start, List path, List> ans) { 9 | if (start == s.length()) { 10 | ans.add(new ArrayList<>(path)); 11 | return; 12 | } 13 | 14 | for (int i = start; i < s.length(); ++i) 15 | if (isPalindrome(s, start, i)) { 16 | path.add(s.substring(start, i + 1)); 17 | dfs(s, i + 1, path, ans); 18 | path.remove(path.size() - 1); 19 | } 20 | } 21 | 22 | private boolean isPalindrome(final String s, int l, int r) { 23 | while (l < r) 24 | if (s.charAt(l++) != s.charAt(r--)) 25 | return false; 26 | return true; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /23feb.java: -------------------------------------------------------------------------------- 1 | class T { 2 | public int pro; 3 | public int cap; 4 | public T(int pro, int cap) { 5 | this.pro = pro; 6 | this.cap = cap; 7 | } 8 | } 9 | 10 | class Solution { 11 | public int findMaximizedCapital(int k, int W, int[] Profits, int[] Capital) { 12 | Queue minHeap = new PriorityQueue<>((a, b) -> a.cap - b.cap); 13 | Queue maxHeap = new PriorityQueue<>((a, b) -> b.pro - a.pro); 14 | 15 | for (int i = 0; i < Capital.length; ++i) 16 | minHeap.offer(new T(Profits[i], Capital[i])); 17 | 18 | while (k-- > 0) { 19 | while (!minHeap.isEmpty() && minHeap.peek().cap <= W) 20 | maxHeap.offer(minHeap.poll()); 21 | if (maxHeap.isEmpty()) 22 | break; 23 | W += maxHeap.poll().pro; 24 | } 25 | 26 | return W; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /23jan.java: -------------------------------------------------------------------------------- 1 | /* 997. Find the Town Judge */ 2 | class Solution { 3 | public int findJudge(int n, int[][] trust) { 4 | int[] count = new int[n + 1]; 5 | 6 | for (int[] t : trust) { 7 | --count[t[0]]; 8 | ++count[t[1]]; 9 | } 10 | 11 | for (int i = 1; i < n + 1; ++i) 12 | if (count[i] == n - 1) 13 | return i; 14 | 15 | return -1; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /24feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumDeviation(int[] nums) { 3 | PriorityQueue pq=new PriorityQueue<>(Collections.reverseOrder()); 4 | int minValue=Integer.MAX_VALUE; 5 | for(int x:nums){ 6 | if((x&1)==1) 7 | x<<=1; 8 | pq.add(x); 9 | minValue=Math.min(minValue,x); 10 | } 11 | int minDeviation=Integer.MAX_VALUE; 12 | while(!pq.isEmpty()){ 13 | int curr=pq.poll(); 14 | minDeviation=Math.min(minDeviation,curr-minValue); 15 | if((curr&1)==1) 16 | break; 17 | curr>>=1; 18 | minValue=Math.min(minValue,curr); 19 | pq.add(curr); 20 | } 21 | return minDeviation; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /24jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findJudge(int n, int[][] trust) { 3 | int[] count = new int[n + 1]; 4 | 5 | for (int[] t : trust) { 6 | --count[t[0]]; 7 | ++count[t[1]]; 8 | } 9 | 10 | for (int i = 1; i < n + 1; ++i) 11 | if (count[i] == n - 1) 12 | return i; 13 | 14 | return -1; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /25Jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int closestMeetingNode(int[] edges, int node1, int node2) { 3 | int[] distanceArray1 = getDistanceArray(edges, node1); 4 | int[] distanceArray2 = getDistanceArray(edges, node2); 5 | 6 | int minDistance = Integer.MAX_VALUE; 7 | int result = -1; 8 | 9 | for (int i = 0; i < edges.length; i++) { 10 | if (distanceArray1[i] == -1 || distanceArray2[i] == -1) continue; 11 | 12 | int distance = Math.max(distanceArray1[i], distanceArray2[i]); 13 | if (distance < minDistance) { 14 | result = i; 15 | minDistance = distance; 16 | } 17 | } 18 | return result; 19 | } 20 | 21 | private int[] getDistanceArray(int[] edges, int node) { 22 | int[] distanceArray = new int[edges.length]; 23 | Arrays.fill(distanceArray, -1); 24 | 25 | int distance = 0; 26 | while (node != -1 && distanceArray[node] == -1) { 27 | distanceArray[node] = distance++; 28 | node = edges[node]; 29 | } 30 | return distanceArray; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /25feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices) { 3 | int sellOne = 0; 4 | int holdOne = Integer.MIN_VALUE; 5 | 6 | for (final int price : prices) { 7 | sellOne = Math.max(sellOne, holdOne + price); 8 | holdOne = Math.max(holdOne, -price); 9 | } 10 | 11 | return sellOne; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /25jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int snakesAndLadders(int[][] board) { 3 | final int n = board.length; 4 | int ans = 0; 5 | Queue q = new ArrayDeque<>(Arrays.asList(1)); 6 | boolean[] seen = new boolean[1 + n * n]; 7 | int[] A = new int[1 + n * n]; // 2D -> 1D 8 | 9 | for (int i = 0; i < n; ++i) 10 | for (int j = 0; j < n; ++j) 11 | A[(n - 1 - i) * n + ((n - i & 1) == 1 ? j + 1 : n - j)] = board[i][j]; 12 | 13 | while (!q.isEmpty()) { 14 | ++ans; 15 | for (int sz = q.size(); sz > 0; --sz) { 16 | final int curr = q.poll(); 17 | for (int next = curr + 1; next <= Math.min(curr + 6, n * n); ++next) { 18 | final int dest = A[next] > 0 ? A[next] : next; 19 | if (dest == n * n) 20 | return ans; 21 | if (seen[dest]) 22 | continue; 23 | q.offer(dest); 24 | seen[dest] = true; 25 | } 26 | } 27 | } 28 | 29 | return -1; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /26feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minDistance(String word1, String word2) { 3 | final int m = word1.length(); 4 | final int n = word2.length(); 5 | // dp[i][j] := min # of operations to convert word1[0..i) to word2[0..j) 6 | int[][] dp = new int[m + 1][n + 1]; 7 | 8 | for (int i = 1; i <= m; ++i) 9 | dp[i][0] = i; 10 | 11 | for (int j = 1; j <= n; ++j) 12 | dp[0][j] = j; 13 | 14 | for (int i = 1; i <= m; ++i) 15 | for (int j = 1; j <= n; ++j) 16 | if (word1.charAt(i - 1) == word2.charAt(j - 1)) 17 | dp[i][j] = dp[i - 1][j - 1]; 18 | else 19 | dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1; 20 | 21 | return dp[m][n]; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /26jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { 3 | List>[] graph = new List[n]; 4 | // (d, u, stops) 5 | Queue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); 6 | int[][] dist = new int[n][k + 2]; 7 | Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); 8 | 9 | for (int i = 0; i < n; ++i) 10 | graph[i] = new ArrayList<>(); 11 | 12 | for (int[] f : flights) { 13 | final int u = f[0]; 14 | final int v = f[1]; 15 | final int w = f[2]; 16 | graph[u].add(new Pair<>(v, w)); 17 | } 18 | 19 | minHeap.offer(new int[] {0, src, k + 1}); // Start with node src with d == 0 20 | dist[src][k + 1] = 0; 21 | 22 | while (!minHeap.isEmpty()) { 23 | final int d = minHeap.peek()[0]; 24 | final int u = minHeap.peek()[1]; 25 | final int stops = minHeap.poll()[2]; 26 | if (u == dst) 27 | return d; 28 | if (stops > 0) 29 | for (Pair pair : graph[u]) { 30 | final int v = pair.getKey(); 31 | final int w = pair.getValue(); 32 | final int newDist = d + w; 33 | if (newDist < dist[v][stops - 1]) { 34 | dist[v][stops - 1] = newDist; 35 | minHeap.offer(new int[] {d + w, v, stops - 1}); 36 | } 37 | } 38 | } 39 | 40 | return -1; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /27jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List findAllConcatenatedWordsInADict(String[] words) { 3 | List ans = new ArrayList<>(); 4 | Set wordSet = new HashSet<>(Arrays.asList(words)); 5 | Map memo = new HashMap<>(); 6 | 7 | for (final String word : words) 8 | if (wordBreak(word, wordSet, memo)) 9 | ans.add(word); 10 | 11 | return ans; 12 | } 13 | 14 | private boolean wordBreak(final String word, Set wordSet, Map memo) { 15 | if (memo.containsKey(word)) 16 | return memo.get(word); 17 | 18 | for (int i = 1; i < word.length(); ++i) { 19 | final String prefix = word.substring(0, i); 20 | final String suffix = word.substring(i); 21 | if (wordSet.contains(prefix) && 22 | (wordSet.contains(suffix) || wordBreak(suffix, wordSet, memo))) { 23 | memo.put(word, true); 24 | return true; 25 | } 26 | } 27 | 28 | memo.put(word, false); 29 | return false; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /28feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List findDuplicateSubtrees(TreeNode root) { 3 | List ans = new ArrayList<>(); 4 | Map count = new HashMap<>(); 5 | encode(root, count, ans); 6 | return ans; 7 | } 8 | 9 | private String encode(TreeNode root, Map count, List ans) { 10 | if (root == null) 11 | return ""; 12 | 13 | final String encoded = 14 | root.val + "#" + encode(root.left, count, ans) + "#" + encode(root.right, count, ans); 15 | count.merge(encoded, 1, Integer::sum); 16 | if (count.get(encoded) == 2) 17 | ans.add(root); 18 | return encoded; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /28jan.java: -------------------------------------------------------------------------------- 1 | class SummaryRanges { 2 | public void addNum(int val) { 3 | if (map.containsKey(val)) 4 | return; 5 | 6 | final Integer lo = map.lowerKey(val); // Maximum in map < key 7 | final Integer hi = map.higherKey(val); // Minimum in map > key 8 | 9 | // {lo, map.get(lo)[1]} + val + {hi, map.get(hi)[1]} = {lo, map.get(hi)[1]} 10 | if (lo != null && hi != null && map.get(lo)[1] + 1 == val && val + 1 == hi) { 11 | map.get(lo)[1] = map.get(hi)[1]; 12 | map.remove(hi); 13 | // {lo, map.get(lo)[1]} + val = {lo, val} 14 | // (prevent adding duplicate entry by using '>=' instead of '==') 15 | } else if (lo != null && map.get(lo)[1] + 1 >= val) { 16 | map.get(lo)[1] = Math.max(map.get(lo)[1], val); 17 | // Val + {hi, map.get(hi)[1]} = {val, map.get(hi)[1]} 18 | } else if (hi != null && val + 1 == hi) { 19 | map.put(val, new int[] {val, map.get(hi)[1]}); 20 | map.remove(hi); 21 | } else { 22 | map.put(val, new int[] {val, val}); 23 | } 24 | } 25 | 26 | public int[][] getIntervals() { 27 | List intervals = new ArrayList<>(map.values()); 28 | return intervals.toArray(new int[intervals.size()][]); 29 | } 30 | 31 | // {start: {start, end}} 32 | private TreeMap map = new TreeMap<>(); 33 | } 34 | -------------------------------------------------------------------------------- /29jan.java: -------------------------------------------------------------------------------- 1 | class LFUCache { 2 | public LFUCache(int capacity) { 3 | this.capacity = capacity; 4 | } 5 | 6 | public int get(int key) { 7 | if (!keyToVal.containsKey(key)) 8 | return -1; 9 | 10 | final int freq = keyToFreq.get(key); 11 | freqToLRUKeys.get(freq).remove(key); 12 | if (freq == minFreq && freqToLRUKeys.get(freq).isEmpty()) { 13 | freqToLRUKeys.remove(freq); 14 | ++minFreq; 15 | } 16 | 17 | // Increase key's freq by 1 18 | // Add this key to next freq's list 19 | putFreq(key, freq + 1); 20 | return keyToVal.get(key); 21 | } 22 | 23 | public void put(int key, int value) { 24 | if (capacity == 0) 25 | return; 26 | if (keyToVal.containsKey(key)) { 27 | keyToVal.put(key, value); 28 | get(key); // Update key's count 29 | return; 30 | } 31 | 32 | if (keyToVal.size() == capacity) { 33 | // Evict LRU key from the minFreq list 34 | final int keyToEvict = freqToLRUKeys.get(minFreq).iterator().next(); 35 | freqToLRUKeys.get(minFreq).remove(keyToEvict); 36 | keyToVal.remove(keyToEvict); 37 | } 38 | 39 | minFreq = 1; 40 | putFreq(key, minFreq); // Add new key and freq 41 | keyToVal.put(key, value); // Add new key and value 42 | } 43 | 44 | private int capacity; 45 | private int minFreq = 0; 46 | private Map keyToVal = new HashMap<>(); 47 | private Map keyToFreq = new HashMap<>(); 48 | private Map> freqToLRUKeys = new HashMap<>(); 49 | 50 | private void putFreq(int key, int freq) { 51 | keyToFreq.put(key, freq); 52 | freqToLRUKeys.putIfAbsent(freq, new LinkedHashSet<>()); 53 | freqToLRUKeys.get(freq).add(key); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /2feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isAlienSorted(String[] words, String order) { 3 | char[] map = new char[26]; // Order = "bca" -> map = ['c', 'a', 'b'] 4 | 5 | for (int i = 0; i < 26; ++i) 6 | map[order.charAt(i) - 'a'] = (char) (i + 'a'); 7 | 8 | for (int i = 0; i + 1 < words.length; ++i) 9 | if (bigger(words[i], words[i + 1], map)) 10 | return false; 11 | 12 | return true; 13 | } 14 | 15 | private boolean bigger(final String s1, final String s2, final char[] map) { 16 | for (int i = 0; i < s1.length() && i < s2.length(); ++i) 17 | if (s1.charAt(i) != s2.charAt(i)) 18 | return map[s1.charAt(i) - 'a'] > map[s2.charAt(i) - 'a']; 19 | return s1.length() > s2.length(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /2mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int compress(char[] chars) { 3 | int ans = 0; 4 | 5 | for (int i = 0; i < chars.length;) { 6 | final char letter = chars[i]; 7 | int count = 0; 8 | while (i < chars.length && chars[i] == letter) { 9 | ++count; 10 | ++i; 11 | } 12 | chars[ans++] = letter; 13 | if (count > 1) 14 | for (final char c : String.valueOf(count).toCharArray()) 15 | chars[ans++] = c; 16 | } 17 | 18 | return ans; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /2ndJan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean detectCapitalUse(String word) { 3 | return word.equals(word.toUpperCase()) || 4 | word.substring(1).equals(word.substring(1).toLowerCase()); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /30jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int tribonacci(int n) { 3 | int[] dp = new int[Math.max(n + 1, 3)]; 4 | dp[1] = dp[2] = 1; 5 | for (int i = 3; i <= n; i++) { 6 | dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]; 7 | } 8 | return dp[n]; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /31jan.java: -------------------------------------------------------------------------------- 1 | class Player { 2 | public int age; 3 | public int score; 4 | public Player(int age, int score) { 5 | this.age = age; 6 | this.score = score; 7 | } 8 | }; 9 | 10 | class Solution { 11 | public int bestTeamScore(int[] scores, int[] ages) { 12 | final int n = scores.length; 13 | Player[] players = new Player[n]; 14 | // dp[i] := max score of choosing players[0..i] w/ players[i] being selected 15 | int[] dp = new int[n]; 16 | 17 | for (int i = 0; i < n; ++i) 18 | players[i] = new Player(ages[i], scores[i]); 19 | 20 | Arrays.sort(players, (a, b) -> a.age == b.age ? b.score - a.score : b.age - a.age); 21 | 22 | for (int i = 0; i < n; ++i) { 23 | // For each player, we choose it first 24 | dp[i] = players[i].score; 25 | // players[j].age >= players[i].age since we sort in descending order 26 | // So we only have to check that 27 | // players[j].score >= players[i].score 28 | for (int j = 0; j < i; ++j) 29 | if (players[j].score >= players[i].score) 30 | dp[i] = Math.max(dp[i], dp[j] + players[i].score); 31 | } 32 | 33 | return Arrays.stream(dp).max().getAsInt(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /3feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String convert(String s, int numRows) { 3 | StringBuilder sb = new StringBuilder(); 4 | List[] rows = new List[numRows]; 5 | int k = 0; 6 | int direction = numRows == 1 ? 0 : -1; 7 | 8 | for (int i = 0; i < numRows; ++i) 9 | rows[i] = new ArrayList<>(); 10 | 11 | for (final char c : s.toCharArray()) { 12 | rows[k].add(c); 13 | if (k == 0 || k == numRows - 1) 14 | direction *= -1; 15 | k += direction; 16 | } 17 | 18 | for (List row : rows) 19 | for (final char c : row) 20 | sb.append(c); 21 | 22 | return sb.toString(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /3mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int strStr(String haystack, String needle) { 3 | final int m = haystack.length(); 4 | final int n = needle.length(); 5 | 6 | for (int i = 0; i < m - n + 1; ++i) 7 | if (haystack.substring(i, i + n).equals(needle)) 8 | return i; 9 | 10 | return -1; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /3rdJan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minDeletionSize(String[] A) { 3 | final int n = A[0].length(); 4 | int ans = 0; 5 | 6 | for (int j = 0; j < n; ++j) 7 | for (int i = 0; i + 1 < A.length; ++i) 8 | if (A[i].charAt(j) > A[i + 1].charAt(j)) { 9 | ++ans; 10 | break; 11 | } 12 | 13 | return ans; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /4feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean checkInclusion(String s1, String s2) { 3 | int[] count = new int[128]; 4 | int required = s1.length(); 5 | 6 | for (final char c : s1.toCharArray()) 7 | ++count[c]; 8 | 9 | for (int l = 0, r = 0; r < s2.length(); ++r) { 10 | if (--count[s2.charAt(r)] >= 0) 11 | --required; 12 | while (required == 0) { 13 | if (r - l + 1 == s1.length()) 14 | return true; 15 | if (++count[s2.charAt(l++)] > 0) 16 | ++required; 17 | } 18 | } 19 | 20 | return false; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /4mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long countSubarrays(int[] nums, int minK, int maxK) { 3 | long ans = 0; 4 | int j = -1; 5 | int prevMinKIndex = -1; 6 | int prevMaxKIndex = -1; 7 | 8 | for (int i = 0; i < nums.length; ++i) { 9 | if (nums[i] < minK || nums[i] > maxK) 10 | j = i; 11 | if (nums[i] == minK) 12 | prevMinKIndex = i; 13 | if (nums[i] == maxK) 14 | prevMaxKIndex = i; 15 | // any index k in [j + 1, min(prevMinKIndex, prevMaxKIndex)] can be the 16 | // start of the subarray s.t. nums[k..i] satisfies the conditions 17 | ans += Math.max(0, Math.min(prevMinKIndex, prevMaxKIndex) - j); 18 | } 19 | 20 | return ans; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /4thJan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumRounds(int[] tasks) { 3 | int ans = 0; 4 | Map count = new HashMap<>(); 5 | 6 | for (final int task : tasks) 7 | count.merge(task, 1, Integer::sum); 8 | 9 | // Freq = 1 -> impossible 10 | // Freq = 2 -> needs 1 round 11 | // Freq = 3 -> needs 1 round 12 | // Freq = 3k -> needs k rounds 13 | // Freq = 3k + 1 = 3 * (k - 1) + 2 * 2 -> needs k + 1 rounds 14 | // Freq = 3k + 2 = 3 * k + 2 * 1 -> needs k + 1 rounds 15 | for (final int freq : count.values()) 16 | if (freq == 1) 17 | return -1; 18 | else 19 | ans += (freq + 2) / 3; 20 | 21 | return ans; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /5feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List findAnagrams(String s, String p) { 3 | List ans = new ArrayList<>(); 4 | int[] count = new int[128]; 5 | int required = p.length(); 6 | 7 | for (final char c : p.toCharArray()) 8 | ++count[c]; 9 | 10 | for (int l = 0, r = 0; r < s.length(); ++r) { 11 | if (--count[s.charAt(r)] >= 0) 12 | --required; 13 | while (required == 0) { 14 | if (r - l + 1 == p.length()) 15 | ans.add(l); 16 | if (++count[s.charAt(l++)] > 0) 17 | ++required; 18 | } 19 | } 20 | 21 | return ans; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /5thJan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMinArrowShots(int[][] points) { 3 | int result = 0; 4 | PriorityQueue priorityQueue = new PriorityQueue<>((a,b) -> a[1]-b[1]); 5 | for (int []point : points) priorityQueue.add(point); 6 | if (priorityQueue.isEmpty()) return 0; 7 | while (!priorityQueue.isEmpty()) { 8 | int [] prev = priorityQueue.poll(); 9 | while (!priorityQueue.isEmpty() && prev[1]>=priorityQueue.peek()[0] && prev[1]<=priorityQueue.peek()[1]) { 10 | priorityQueue.poll(); 11 | } 12 | result++; 13 | } 14 | return result; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /6jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] shuffle(int[] nums, int n) { 3 | int count = 0; 4 | int[] arr = new int[2*n]; 5 | for(int i=0; i< n;i++){ 6 | arr[count] = nums[i]; 7 | arr[count+1]=nums[i+n]; 8 | count +=2; 9 | } 10 | return arr; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /6thJan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxIceCream(int[] costs, int coins) { 3 | Arrays.sort(costs); 4 | 5 | for (int i = 0; i < costs.length; ++i) 6 | if (coins >= costs[i]) 7 | coins -= costs[i]; 8 | else 9 | return i; 10 | 11 | return costs.length; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /7feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int totalFruit(int[] tree) { 3 | int ans = 0; 4 | Map count = new HashMap<>(); 5 | 6 | for (int l = 0, r = 0; r < tree.length; ++r) { 7 | count.put(tree[r], count.getOrDefault(tree[r], 0) + 1); 8 | while (count.size() > 2) { 9 | count.put(tree[l], count.get(tree[l]) - 1); 10 | count.remove(tree[l], 0); 11 | ++l; 12 | } 13 | ans = Math.max(ans, r - l + 1); 14 | } 15 | 16 | return ans; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /7thJan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int canCompleteCircuit(int[] gas, int[] cost) { 3 | final int gasses = Arrays.stream(gas).sum(); 4 | final int costs = Arrays.stream(cost).sum(); 5 | if (gasses - costs < 0) 6 | return -1; 7 | 8 | int ans = 0; 9 | int sum = 0; 10 | 11 | // Try to start from each index 12 | for (int i = 0; i < gas.length; ++i) { 13 | sum += gas[i] - cost[i]; 14 | if (sum < 0) { 15 | sum = 0; 16 | ans = i + 1; // Start from next index 17 | } 18 | } 19 | 20 | return ans; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /8Jan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxPoints(int[][] points) { 3 | int N=points.length; 4 | if(N<2) 5 | return N; 6 | HashMap hm = new HashMap<>(); 7 | int curr_max,vertical,same,horizontal; 8 | int max=0; 9 | for(int i=0;i= nums.length - 1) { 11 | ++ans; 12 | break; 13 | } 14 | if (i == end) { // visited all the items on the current level 15 | ++ans; // increment the level 16 | end = farthest; // make the queue size for the next level 17 | } 18 | } 19 | 20 | return ans; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /9feb.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long distinctNames(String[] ideas) { 3 | long ans = 0; 4 | // Group strings by initials 5 | Set[] suffixes = new Set[26]; 6 | 7 | for (int i = 0; i < 26; ++i) 8 | suffixes[i] = new HashSet<>(); 9 | 10 | for (final String idea : ideas) 11 | suffixes[idea.charAt(0) - 'a'].add(idea.substring(1)); 12 | 13 | for (int i = 0; i < 25; ++i) 14 | for (int j = i + 1; j < 26; ++j) { 15 | int count = 0; 16 | for (final String suffix : suffixes[i]) 17 | if (suffixes[j].contains(suffix)) 18 | ++count; 19 | ans += 2 * (suffixes[i].size() - count) * (suffixes[j].size() - count); 20 | } 21 | 22 | return ans; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /9thJan.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List preorderTraversal(TreeNode root) { 3 | List ans = new ArrayList<>(); 4 | preorder(root, ans); 5 | return ans; 6 | } 7 | 8 | private void preorder(TreeNode root, List ans) { 9 | if (root == null) 10 | return; 11 | 12 | ans.add(root.val); 13 | preorder(root.left, ans); 14 | preorder(root.right, ans); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /April/11apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String removeStars(String s) { 3 | StringBuilder sb = new StringBuilder(); 4 | for (final char c : s.toCharArray()) 5 | if (c == '*') 6 | sb.deleteCharAt(sb.length() - 1); 7 | else 8 | sb.append(c); 9 | return sb.toString(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /April/12apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String simplifyPath(String path) { 3 | final String[] dirs = path.split("/"); 4 | Stack stack = new Stack<>(); 5 | 6 | for (final String dir : dirs) { 7 | if (dir.isEmpty() || dir.equals(".")) 8 | continue; 9 | if (dir.equals("..")) { 10 | if (!stack.isEmpty()) 11 | stack.pop(); 12 | } else { 13 | stack.push(dir); 14 | } 15 | } 16 | 17 | return "/" + String.join("/", stack); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /April/13apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean validateStackSequences(int[] pushed, int[] popped) { 3 | Deque stack = new ArrayDeque<>(); 4 | int i = 0; // popped's index 5 | 6 | for (final int x : pushed) { 7 | stack.push(x); 8 | while (!stack.isEmpty() && stack.peek() == popped[i]) { 9 | stack.pop(); 10 | ++i; 11 | } 12 | } 13 | 14 | return stack.isEmpty(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /April/15apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxValueOfCoins(List> piles, int k) { 3 | // dp[i][k] := max value of picking k coins from piles[i:] 4 | dp = new Integer[piles.size()][k + 1]; 5 | return maxValueOfCoins(piles, 0, k); 6 | } 7 | 8 | private Integer[][] dp; 9 | 10 | private int maxValueOfCoins(List> piles, int i, int k) { 11 | if (i == piles.size() || k == 0) 12 | return 0; 13 | if (dp[i][k] != null) 14 | return dp[i][k]; 15 | 16 | int ans = maxValueOfCoins(piles, i + 1, k); // Pick 0 coins from current pile 17 | int val = 0; // Coins picked from current pile 18 | 19 | // Try to pick 1, 2, ..., k coins from current pile 20 | for (int j = 0; j < Math.min(piles.get(i).size(), k); ++j) { 21 | val += piles.get(i).get(j); 22 | ans = Math.max(ans, val + maxValueOfCoins(piles, i + 1, k - j - 1)); 23 | } 24 | 25 | return dp[i][k] = ans; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /April/16apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numWays(String[] words, String target) { 3 | int mod = 1000000007; 4 | int n = words[0].length(); 5 | int[][] freq = new int[n][26]; // freq[i][j] = frequency of j+'a' in the ith column of the matrix 6 | 7 | for (int i = 0; i < words.length; i++) { 8 | for (int j = 0; j < n; j++) { 9 | freq[j][words[i].charAt(j) - 'a']++; 10 | } 11 | } 12 | 13 | int[][] dp = new int[n+1][target.length()+1]; // dp[i][j] = number of ways to form the prefix of target with length j using the first i columns of the matrix 14 | 15 | for (int i = 0; i <= n; i++) { 16 | dp[i][0] = 1; 17 | } 18 | 19 | for (int i = 1; i <= n; i++) { 20 | for (int j = 1; j <= target.length(); j++) { 21 | int charCount = freq[i-1][target.charAt(j-1) - 'a']; 22 | dp[i][j] = (dp[i-1][j] + (int)((long)charCount * dp[i-1][j-1] % mod)) % mod; 23 | } 24 | } 25 | 26 | return dp[n][target.length()]; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /April/17apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List kidsWithCandies(int[] candies, int extraCandies) { 3 | List result = new ArrayList<>(); 4 | 5 | int max=0; 6 | 7 | for(int candy : candies){ 8 | if(candy>max) 9 | { 10 | max=candy; 11 | } 12 | } 13 | 14 | max= max-extraCandies; 15 | for(int z: candies ) 16 | { 17 | result.add(z>=max); 18 | 19 | } 20 | return result; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /April/18apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String mergeAlternately(String word1, String word2) { 3 | final int n = Math.min(word1.length(), word2.length()); 4 | StringBuilder sb = new StringBuilder(); 5 | 6 | for (int i = 0; i < n; ++i) { 7 | sb.append(word1.charAt(i)); 8 | sb.append(word2.charAt(i)); 9 | } 10 | 11 | return sb.append(word1.substring(n)).append(word2.substring(n)).toString(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /April/19apr.java: -------------------------------------------------------------------------------- 1 | class T { 2 | public int leftMax; 3 | public int rightMax; 4 | public int subtreeMax; 5 | 6 | public T(int leftMax, int rightMax, int subtreeMax) { 7 | this.leftMax = leftMax; 8 | this.rightMax = rightMax; 9 | this.subtreeMax = subtreeMax; 10 | } 11 | } 12 | 13 | class Solution { 14 | public int longestZigZag(TreeNode root) { 15 | return dfs(root).subtreeMax; 16 | } 17 | 18 | private T dfs(TreeNode root) { 19 | if (root == null) 20 | return new T(-1, -1, -1); 21 | T left = dfs(root.left); 22 | T right = dfs(root.right); 23 | final int leftZigZag = left.rightMax + 1; 24 | final int rightZigZag = right.leftMax + 1; 25 | final int subtreeMax = 26 | Math.max(Math.max(leftZigZag, rightZigZag), Math.max(left.subtreeMax, right.subtreeMax)); 27 | return new T(leftZigZag, rightZigZag, subtreeMax); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /April/1apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int search(int[] nums, int target) { 3 | int n=nums.length-1; 4 | int start=0; 5 | int end=n,mid; 6 | 7 | while(start <= end) 8 | { 9 | mid=(start + end)/2; 10 | if(nums[mid] == target) return mid; 11 | else 12 | { 13 | if(target>nums[mid]) start=mid+1; 14 | else end = mid -1; 15 | } 16 | } 17 | return -1; 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /April/2apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] successfulPairs(int[] spells, int[] potions, long success) { 3 | int[] ans = new int[spells.length]; 4 | Arrays.sort(potions); 5 | 6 | for (int i = 0; i < spells.length; ++i) 7 | ans[i] = potions.length - firstIndexSuccess(spells[i], potions, success); 8 | 9 | return ans; 10 | } 11 | 12 | // First index i s.t. spell * potions[i] >= success 13 | private int firstIndexSuccess(int spell, int[] potions, long success) { 14 | int l = 0; 15 | int r = potions.length; 16 | while (l < r) { 17 | final int m = (l + r) / 2; 18 | if ((long) spell * potions[m] >= success) 19 | r = m; 20 | else 21 | l = m + 1; 22 | } 23 | return l; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /April/3apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numRescueBoats(int[] people, int limit) { 3 | int ans = 0; 4 | 5 | Arrays.sort(people); 6 | 7 | for (int i = 0, j = people.length - 1; i <= j; ++ans) { 8 | int remain = limit - people[j--]; 9 | if (people[i] <= remain) 10 | ++i; 11 | } 12 | 13 | return ans; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /April/4apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int partitionString(String s) { 3 | int ans = 1; 4 | int usedMask = 0; 5 | 6 | for (final char c : s.toCharArray()) { 7 | final int i = c - 'a'; 8 | if ((usedMask >> i & 1) == 1) { 9 | usedMask = 1 << i; 10 | ++ans; 11 | } else { 12 | usedMask |= 1 << i; 13 | } 14 | } 15 | 16 | return ans; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /April/5apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimizeArrayValue(int[] nums) { 3 | long ans = 0; 4 | long prefix = 0; 5 | 6 | for (int i = 0; i < nums.length; ++i) { 7 | prefix += nums[i]; 8 | final long prefixAvg = (long) Math.ceil(prefix / (double) (i + 1)); 9 | ans = Math.max(ans, prefixAvg); 10 | } 11 | 12 | return (int) ans; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /April/6apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int closedIsland(int[][] grid) { 3 | final int m = grid.length; 4 | final int n = grid[0].length; 5 | 6 | // Remove lands connected to edge 7 | for (int i = 0; i < m; ++i) 8 | for (int j = 0; j < n; ++j) 9 | if (i * j == 0 || i == m - 1 || j == n - 1) 10 | if (grid[i][j] == 0) 11 | dfs(grid, i, j); 12 | 13 | int ans = 0; 14 | 15 | // Reduce to 200. Number of Islands 16 | for (int i = 0; i < m; ++i) 17 | for (int j = 0; j < n; ++j) 18 | if (grid[i][j] == 0) { 19 | dfs(grid, i, j); 20 | ++ans; 21 | } 22 | 23 | return ans; 24 | } 25 | 26 | private void dfs(int[][] grid, int i, int j) { 27 | if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) 28 | return; 29 | if (grid[i][j] == 1) 30 | return; 31 | 32 | grid[i][j] = 1; 33 | dfs(grid, i + 1, j); 34 | dfs(grid, i - 1, j); 35 | dfs(grid, i, j + 1); 36 | dfs(grid, i, j - 1); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /April/7apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numEnclaves(int[][] A) { 3 | final int m = A.length; 4 | final int n = A[0].length; 5 | 6 | // Remove lands connected to edge 7 | for (int i = 0; i < m; ++i) 8 | for (int j = 0; j < n; ++j) 9 | if (i * j == 0 || i == m - 1 || j == n - 1) 10 | if (A[i][j] == 1) 11 | dfs(A, i, j); 12 | 13 | int ans = 0; 14 | 15 | for (int[] row : A) 16 | ans += Arrays.stream(row).sum(); 17 | 18 | return ans; 19 | } 20 | 21 | private void dfs(int[][] A, int i, int j) { 22 | if (i < 0 || i == A.length || j < 0 || j == A[0].length) 23 | return; 24 | if (A[i][j] == 0) 25 | return; 26 | 27 | A[i][j] = 0; 28 | dfs(A, i + 1, j); 29 | dfs(A, i - 1, j); 30 | dfs(A, i, j + 1); 31 | dfs(A, i, j - 1); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /April/8apr.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public Node cloneGraph(Node node) { 3 | if (node == null) 4 | return null; 5 | 6 | Queue q = new ArrayDeque<>(Arrays.asList(node)); 7 | Map map = new HashMap<>(); 8 | map.put(node, new Node(node.val)); 9 | 10 | while (!q.isEmpty()) { 11 | Node u = q.poll(); 12 | for (Node v : u.neighbors) { 13 | if (!map.containsKey(v)) { 14 | map.put(v, new Node(v.val)); 15 | q.offer(v); 16 | } 17 | map.get(u).neighbors.add(map.get(v)); 18 | } 19 | } 20 | 21 | return map.get(node); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Contests/4ma.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long coloredCells(int n) { 3 | return 2l * n * (n - 1) + 1; 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Contests/4mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int splitNum(int num) { 4 | char[] ca = Integer.toString(num).toCharArray(); 5 | Arrays.sort(ca); 6 | int a = 0, b = 0; 7 | for (int i = 0; i < ca.length; ++i) { 8 | int digit = ca[i] - '0'; 9 | if (i % 2 == 0) { 10 | a *= 10; 11 | a += digit; 12 | }else { 13 | b *= 10; 14 | b += digit; 15 | } 16 | } 17 | return a + b; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Contests/4marc.java: -------------------------------------------------------------------------------- 1 | public int countWays(int[][] ranges) { 2 | int res = 1, last = -1, mod = (int)1e9 + 7; 3 | Arrays.sort(ranges, (a, b) -> a[0] - b[0]); 4 | for (int[] r: ranges) { 5 | if (last < r[0]) 6 | res = res * 2 % mod; 7 | last = Math.max(last, r[1]); 8 | } 9 | return res; 10 | } 11 | -------------------------------------------------------------------------------- /Contests/4march.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Solution{ 3 | HashSet ans=new HashSet<>(); 4 | public void DFS(ArrayList[]arr,HashSet h) 5 | { boolean []bool=new boolean[arr.length+1]; 6 | for(int i=1;i []arr,boolean []vst,int i,HashSet h) { 15 | if (vst[i]) { 16 | return; 17 | } 18 | vst[i] = true; 19 | // cc++;; 20 | ArrayList anss = arr[i]; 21 | if (anss != null) { 22 | for (Integer an : anss) { 23 | { 24 | if (vst[an]) { 25 | continue; 26 | } 27 | // dfs.add(an); 28 | String s = ""; 29 | s += i + "#" + an; 30 | if (h.contains(s)) 31 | ans.add(s); 32 | DFS(arr, vst, an, h); 33 | } 34 | } 35 | } 36 | } 37 | public int rootCount(int[][] edges, int[][] gs, int k) { 38 | if(k==0) 39 | { 40 | return edges.length+1; 41 | } 42 | int m=edges.length; 43 | int n=m+1; 44 | int [][]gp=new int[m][2]; 45 | ans=new HashSet<>(); 46 | ArrayList[]arr=new ArrayList[n+1]; 47 | for(int i=0;i ans=new ArrayList<>(); 54 | if(arr[gp[i][0]]!=null) 55 | { 56 | ans=arr[gp[i][0]]; 57 | } 58 | ans.add(gp[i][1]); 59 | arr[gp[i][0]]=ans; 60 | ArrayList bns=new ArrayList<>(); 61 | if(arr[gp[i][1]]!=null) 62 | { 63 | bns=arr[gp[i][1]]; 64 | } 65 | bns.add(gp[i][0]); 66 | arr[gp[i][1]]=bns; 67 | } 68 | HashSet h=new HashSet<>(); 69 | for (int[] g : gs) { 70 | String a = "" + (g[0] + 1) + "#" + (g[1] + 1); 71 | h.add(a); 72 | } 73 | DFS(arr,h); 74 | return BFS(arr,h,k,n); 75 | } 76 | public int BFS(ArrayList[]arr,HashSet h,int k,int n) 77 | { 78 | Queue q=new LinkedList<>(); 79 | boolean []vst=new boolean[arr.length]; 80 | int sizer[]=new int[arr.length]; 81 | sizer[1]=ans.size(); 82 | q.offer(1); 83 | while(!q.isEmpty()) 84 | { int x=q.poll(); 85 | if(!vst[x]) { 86 | // bfs.add(x); 87 | vst[x]=true; 88 | ArrayList anss=arr[x]; 89 | for (Integer an : anss) { 90 | if(!vst[an]) 91 | { sizer[an]=sizer[x]; 92 | String torem="",toadd=""; 93 | torem+=x+"#"+an; 94 | if(h.contains(torem)) 95 | sizer[an]--; 96 | toadd+=an+"#"+x; 97 | if(h.contains(toadd)) 98 | sizer[an]++; 99 | // System.out.println(torem+"---"+toadd); 100 | q.offer(an); 101 | } 102 | } 103 | } 104 | } 105 | int ak=0; 106 | for(int i=1;i=k) 109 | ak++; 110 | } 111 | return ak; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /Day24.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int snakesAndLadders(vector> &board) { 4 | int n = board.size(); 5 | vector> cells(n * n + 1); 6 | int label = 1; 7 | vector columns(n); 8 | iota(columns.begin(), columns.end(), 0); 9 | for (int row = n - 1; 10 | row >= 0; row--) { 11 | for (int column : columns) { 12 | cells[label++] = {row, column}; 13 | } 14 | reverse(columns.begin(), columns.end()); 15 | } 16 | vector dist(n * n + 1, -1); 17 | queue q; dist[1] = 0; 18 | q.push(1); 19 | while (!q.empty()) { 20 | int curr = q.front(); 21 | q.pop(); 22 | for (int next = curr + 1; 23 | next <= min(curr + 6, n * n); next++) 24 | { 25 | auto [row, column] = cells[next]; 26 | int destination = board[row][column] != -1 ? board[row][column] : next; 27 | if (dist[destination] == -1) 28 | { dist[destination] = dist[curr] + 1; 29 | q.push(destination); 30 | } 31 | } 32 | } return dist[n * n]; 33 | } 34 | }; -------------------------------------------------------------------------------- /Make the array beautiful - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Make the array beautiful 2 | ## Easy 3 |

Given an array of negative and non-negative integers. You have to make the array beautiful. An array is beautiful if two adjacent integers, arr[i] and arr[i+1] are either negative or non-negative. And you can do the following operation any number of times until the array becomes beautiful.

4 | 5 |
    6 |
  • If two adjacent integers are different i.e. one of them is negative and other is non-negative, remove them.
  • 7 |
8 | 9 |

Return the beautiful array after performing the above operation.

10 | 11 |

Note:An empty array is also a beautiful array. There can be many adjacent integers which are different as stated above. So remove different adjacent integers as described above from left to right.

12 | 13 |

Example 1:

14 | 15 |
Input: 4 2 -2 1
16 | Output: 4 1
17 | Explanation: As at indices 1 and 2 , 2 and -2 have
18 | different sign, they are removed. And the  the final
19 | array is: 4 1.
20 | 
21 | 22 |

Example 2:

23 | 24 |
Input: 2 -2 1 -1
25 | Output: []
26 | Explanation: As at indices 0 and 1, 2 and -2 have
27 | different sign, so they are removed. Now the array
28 | is 1 -1.Now 1 and -1 are also removed as they have
29 | different sign. So the final array is empty. 
30 | 31 |

Your Task:
32 | You don't need to read input or print anything. Your task is to complete the function makeBeautiful() which takes an array as an input parameter and returns an array.

33 | 34 |

Expected Time Complexity: O(N)
35 | Expected Space Complexity: O(N)

36 | 37 |


38 | Constraints:
39 | 1 <= size of the array <= 10
5
40 | -105 <= arr[i] <= 105
41 |  

42 | 43 |

 

44 |
-------------------------------------------------------------------------------- /Make the array beautiful - GFG/make-the-array-beautiful.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | // Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | // User function Template for C++ 10 | 11 | class Solution { 12 | public: 13 | vector makeBeautiful(vector arr) { 14 | // code here 15 | 16 | vector res; 17 | 18 | for(auto &x: arr) { 19 | if(res.size() and ((res.back() < 0 and x >= 0) or (res.back() >= 0 and x < 0))) { 20 | res.pop_back(); 21 | } 22 | else res.push_back(x); 23 | } 24 | 25 | return res; 26 | } 27 | }; 28 | 29 | //{ Driver Code Starts. 30 | 31 | int main() { 32 | int t; 33 | cin >> t; 34 | while (t--) { 35 | int n; 36 | cin >> n; 37 | vector arr(n); 38 | for (int i = 0; i < n; i++) { 39 | cin >> arr[i]; 40 | } 41 | 42 | Solution obj; 43 | vector res = obj.makeBeautiful(arr); 44 | for (int i = 0; i < res.size(); i++) { 45 | cout << res[i] << " "; 46 | } 47 | 48 | cout << "\n"; 49 | } 50 | } 51 | // } Driver Code Ends -------------------------------------------------------------------------------- /March/10mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /** 3 | * @param head The linked list's head. Note that the head is guaranteed to be 4 | * not null, so it contains at least one node. 5 | */ 6 | public Solution(ListNode head) { 7 | this.head = head; 8 | } 9 | 10 | /** Returns a random node's value. */ 11 | public int getRandom() { 12 | int ans = -1; 13 | int i = 1; 14 | 15 | for (ListNode curr = head; curr != null; curr = curr.next, ++i) 16 | if (rand.nextInt(i) == i - 1) 17 | ans = curr.val; 18 | 19 | return ans; 20 | } 21 | 22 | private ListNode head; 23 | private Random rand = new Random(); 24 | } 25 | -------------------------------------------------------------------------------- /March/11mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public TreeNode sortedListToBST(ListNode head) { 3 | if (head == null) 4 | return null; 5 | if (head.next == null) 6 | return new TreeNode(head.val); 7 | 8 | ListNode mid = findMid(head); 9 | TreeNode root = new TreeNode(mid.val); 10 | root.left = sortedListToBST(head); 11 | root.right = sortedListToBST(mid.next); 12 | 13 | return root; 14 | } 15 | 16 | private ListNode findMid(ListNode head) { 17 | ListNode prev = null; 18 | ListNode slow = head; 19 | ListNode fast = head; 20 | 21 | while (fast != null && fast.next != null) { 22 | prev = slow; 23 | slow = slow.next; 24 | fast = fast.next.next; 25 | } 26 | prev.next = null; 27 | 28 | return slow; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /March/12mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode mergeKLists(ListNode[] lists) { 3 | ListNode dummy = new ListNode(0); 4 | ListNode curr = dummy; 5 | Queue minHeap = new PriorityQueue<>((a, b) -> a.val - b.val); 6 | 7 | for (final ListNode list : lists) 8 | if (list != null) 9 | minHeap.offer(list); 10 | 11 | while (!minHeap.isEmpty()) { 12 | ListNode minNode = minHeap.poll(); 13 | if (minNode.next != null) 14 | minHeap.offer(minNode.next); 15 | curr.next = minNode; 16 | curr = curr.next; 17 | } 18 | 19 | return dummy.next; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /March/13mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isSymmetric(TreeNode root) { 3 | return isSymmetric(root, root); 4 | } 5 | 6 | private boolean isSymmetric(TreeNode p, TreeNode q) { 7 | if (p == null || q == null) 8 | return p == q; 9 | 10 | return p.val == q.val && isSymmetric(p.left, q.right) && isSymmetric(p.right, q.left); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /March/14mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int sumNumbers(TreeNode root) { 3 | dfs(root, 0); 4 | return ans; 5 | } 6 | 7 | private int ans = 0; 8 | 9 | private void dfs(TreeNode root, int path) { 10 | if (root == null) 11 | return; 12 | if (root.left == null && root.right == null) { 13 | ans += path * 10 + root.val; 14 | return; 15 | } 16 | 17 | dfs(root.left, path * 10 + root.val); 18 | dfs(root.right, path * 10 + root.val); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /March/15mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isCompleteTree(TreeNode root) { 3 | if (root == null) 4 | return true; 5 | 6 | Queue q = new LinkedList<>(Arrays.asList(root)); 7 | 8 | while (q.peek() != null) { 9 | TreeNode node = q.poll(); 10 | q.offer(node.left); 11 | q.offer(node.right); 12 | } 13 | 14 | while (!q.isEmpty() && q.peek() == null) 15 | q.poll(); 16 | 17 | return q.isEmpty(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /March/16mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public TreeNode buildTree(int[] inorder, int[] postorder) { 3 | Map inToIndex = new HashMap<>(); 4 | 5 | for (int i = 0; i < inorder.length; ++i) 6 | inToIndex.put(inorder[i], i); 7 | 8 | return build(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1, inToIndex); 9 | } 10 | 11 | TreeNode build(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd, 12 | Map inToIndex) { 13 | if (inStart > inEnd) 14 | return null; 15 | 16 | final int rootVal = postorder[postEnd]; 17 | final int rootInIndex = inToIndex.get(rootVal); 18 | final int leftSize = rootInIndex - inStart; 19 | 20 | TreeNode root = new TreeNode(rootVal); 21 | root.left = build(inorder, inStart, rootInIndex - 1, postorder, postStart, 22 | postStart + leftSize - 1, inToIndex); 23 | root.right = build(inorder, rootInIndex + 1, inEnd, postorder, postStart + leftSize, 24 | postEnd - 1, inToIndex); 25 | return root; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /March/17mar.java: -------------------------------------------------------------------------------- 1 | class TrieNode { 2 | public TrieNode[] children = new TrieNode[26]; 3 | public boolean isWord = false; 4 | } 5 | 6 | class Trie { 7 | public void insert(String word) { 8 | TrieNode node = root; 9 | for (final char c : word.toCharArray()) { 10 | final int i = c - 'a'; 11 | if (node.children[i] == null) 12 | node.children[i] = new TrieNode(); 13 | node = node.children[i]; 14 | } 15 | node.isWord = true; 16 | } 17 | 18 | public boolean search(String word) { 19 | TrieNode node = find(word); 20 | return node != null && node.isWord; 21 | } 22 | 23 | public boolean startsWith(String prefix) { 24 | return find(prefix) != null; 25 | } 26 | 27 | private TrieNode root = new TrieNode(); 28 | 29 | private TrieNode find(String prefix) { 30 | TrieNode node = root; 31 | for (final char c : prefix.toCharArray()) { 32 | final int i = c - 'a'; 33 | if (node.children[i] == null) 34 | return null; 35 | node = node.children[i]; 36 | } 37 | return node; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /March/18mar.java: -------------------------------------------------------------------------------- 1 | class BrowserHistory { 2 | public BrowserHistory(String homepage) { 3 | visit(homepage); 4 | } 5 | 6 | public void visit(String url) { 7 | if (++index < urls.size()) 8 | urls.set(index, url); 9 | else 10 | urls.add(url); 11 | lastIndex = index; 12 | } 13 | 14 | public String back(int steps) { 15 | index = Math.max(0, index - steps); 16 | return urls.get(index); 17 | } 18 | 19 | public String forward(int steps) { 20 | index = Math.min(lastIndex, index + steps); 21 | return urls.get(index); 22 | } 23 | 24 | private List urls = new ArrayList<>(); 25 | private int index = -1; 26 | private int lastIndex = -1; 27 | } 28 | -------------------------------------------------------------------------------- /March/19mar.java: -------------------------------------------------------------------------------- 1 | class TrieNode { 2 | public TrieNode[] children = new TrieNode[26]; 3 | public boolean isWord = false; 4 | } 5 | 6 | class WordDictionary { 7 | public void addWord(String word) { 8 | TrieNode node = root; 9 | for (final char c : word.toCharArray()) { 10 | final int i = c - 'a'; 11 | if (node.children[i] == null) 12 | node.children[i] = new TrieNode(); 13 | node = node.children[i]; 14 | } 15 | node.isWord = true; 16 | } 17 | 18 | public boolean search(String word) { 19 | return dfs(word, 0, root); 20 | } 21 | 22 | private TrieNode root = new TrieNode(); 23 | 24 | private boolean dfs(String word, int s, TrieNode node) { 25 | if (s == word.length()) 26 | return node.isWord; 27 | if (word.charAt(s) != '.') { 28 | TrieNode next = node.children[word.charAt(s) - 'a']; 29 | return next == null ? false : dfs(word, s + 1, next); 30 | } 31 | 32 | // Word.charAt(s) == '.' -> search all 26 children 33 | for (int i = 0; i < 26; ++i) 34 | if (node.children[i] != null && dfs(word, s + 1, node.children[i])) 35 | return true; 36 | 37 | return false; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /March/20mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canPlaceFlowers(int[] flowerbed, int n) { 3 | if (n == 0) 4 | return true; 5 | 6 | for (int i = 0; i < flowerbed.length; ++i) 7 | if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && 8 | (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) { 9 | flowerbed[i] = 1; 10 | if (--n == 0) 11 | return true; 12 | } 13 | 14 | return false; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /March/21mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long zeroFilledSubarray(int[] nums) { 3 | long ans = 0; 4 | int indexBeforeZero = -1; 5 | 6 | for (int i = 0; i < nums.length; ++i) 7 | if (nums[i] == 0) 8 | ans += i - indexBeforeZero; 9 | else 10 | indexBeforeZero = i; 11 | 12 | return ans; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /March/22mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minScore(int n, int[][] roads) { 3 | int ans = Integer.MAX_VALUE; 4 | List>[] graph = new List[n]; // graph[u] := [(v, distance)] 5 | Queue q = new ArrayDeque<>(Arrays.asList(0)); 6 | boolean[] seen = new boolean[n]; 7 | seen[0] = true; 8 | 9 | for (int i = 0; i < n; ++i) 10 | graph[i] = new ArrayList<>(); 11 | 12 | for (final int[] r : roads) { 13 | final int u = r[0] - 1; 14 | final int v = r[1] - 1; 15 | final int distance = r[2]; 16 | graph[u].add(new Pair<>(v, distance)); 17 | graph[v].add(new Pair<>(u, distance)); 18 | } 19 | 20 | while (!q.isEmpty()) { 21 | final int u = q.poll(); 22 | for (Pair pair : graph[u]) { 23 | final int v = pair.getKey(); 24 | final int d = pair.getValue(); 25 | ans = Math.min(ans, d); 26 | if (seen[v]) 27 | continue; 28 | q.offer(v); 29 | seen[v] = true; 30 | } 31 | } 32 | 33 | return ans; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /March/23mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int makeConnected(int n, int[][] connections) { 3 | // to connect n nodes, we need at least n - 1 edges 4 | if (connections.length < n - 1) 5 | return -1; 6 | 7 | int numOfConnected = 0; 8 | List[] graph = new List[n]; 9 | Set seen = new HashSet<>(); 10 | 11 | for (int i = 0; i < n; ++i) 12 | graph[i] = new ArrayList<>(); 13 | 14 | for (int[] conn : connections) { 15 | graph[conn[0]].add(conn[1]); 16 | graph[conn[1]].add(conn[0]); 17 | } 18 | 19 | for (int i = 0; i < n; ++i) 20 | if (seen.add(i)) { 21 | dfs(graph, i, seen); 22 | ++numOfConnected; 23 | } 24 | 25 | return numOfConnected - 1; 26 | } 27 | 28 | private void dfs(List[] graph, int u, Set seen) { 29 | for (final int v : graph[u]) 30 | if (seen.add(v)) 31 | dfs(graph, v, seen); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /March/24mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minReorder(int n, int[][] connections) { 3 | List[] graph = new List[n]; 4 | 5 | for (int i = 0; i < n; ++i) 6 | graph[i] = new ArrayList<>(); 7 | 8 | for (int[] conn : connections) { 9 | graph[conn[0]].add(conn[1]); 10 | graph[conn[1]].add(-conn[0]); // - := conn[0] -> conn[1] 11 | } 12 | 13 | return dfs(graph, 0, -1); 14 | } 15 | 16 | private int dfs(List[] graph, int u, int parent) { 17 | int change = 0; 18 | 19 | for (final int v : graph[u]) { 20 | if (Math.abs(v) == parent) 21 | continue; 22 | if (v > 0) 23 | ++change; 24 | change += dfs(graph, Math.abs(v), u); 25 | } 26 | 27 | return change; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /March/25mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long countPairs(int n, int[][] edges) { 3 | long ans = 0; 4 | List[] graph = new List[n]; 5 | boolean[] seen = new boolean[n]; 6 | int unreached = n; 7 | 8 | for (int i = 0; i < n; ++i) 9 | graph[i] = new ArrayList<>(); 10 | 11 | for (int[] edge : edges) { 12 | final int u = edge[0]; 13 | final int v = edge[1]; 14 | graph[u].add(v); 15 | graph[v].add(u); 16 | } 17 | 18 | for (int i = 0; i < n; ++i) { 19 | final int reached = dfs(graph, i, seen); 20 | unreached -= reached; 21 | ans += (long) unreached * reached; 22 | } 23 | return ans; 24 | } 25 | 26 | private int dfs(List[] graph, int u, boolean[] seen) { 27 | if (seen[u]) 28 | return 0; 29 | 30 | seen[u] = true; 31 | int ans = 1; 32 | for (final int v : graph[u]) 33 | ans += dfs(graph, v, seen); 34 | return ans; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /March/26mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestCycle(int[] edges) { 3 | int ans = -1; 4 | int time = 1; 5 | int[] timeVisited = new int[edges.length]; 6 | 7 | for (int i = 0; i < edges.length; ++i) { 8 | if (timeVisited[i] > 0) 9 | continue; 10 | final int startTime = time; 11 | int u = i; 12 | while (u != -1 && timeVisited[u] == 0) { 13 | timeVisited[u] = time++; 14 | u = edges[u]; // Move to next node 15 | } 16 | if (u != -1 && timeVisited[u] >= startTime) 17 | ans = Math.max(ans, time - timeVisited[u]); 18 | } 19 | 20 | return ans; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /March/27mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minPathSum(int[][] grid) { 3 | final int m = grid.length; 4 | final int n = grid[0].length; 5 | 6 | for (int i = 0; i < m; ++i) 7 | for (int j = 0; j < n; ++j) 8 | if (i > 0 && j > 0) 9 | grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]); 10 | else if (i > 0) 11 | grid[i][0] += grid[i - 1][0]; 12 | else if (j > 0) 13 | grid[0][j] += grid[0][j - 1]; 14 | 15 | return grid[m - 1][n - 1]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /March/28mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int mincostTickets(int[] days, int[] costs) { 3 | int ans = 0; 4 | Queue last7 = new ArrayDeque<>(); // [day, cost] 5 | Queue last30 = new ArrayDeque<>(); 6 | 7 | for (int day : days) { 8 | while (!last7.isEmpty() && last7.peek()[0] + 7 <= day) 9 | last7.poll(); 10 | while (!last30.isEmpty() && last30.peek()[0] + 30 <= day) 11 | last30.poll(); 12 | last7.offer(new int[] {day, ans + costs[1]}); 13 | last30.offer(new int[] {day, ans + costs[2]}); 14 | ans = Math.min(ans + costs[0], Math.min(last7.peek()[1], last30.peek()[1])); 15 | } 16 | 17 | return ans; 18 | } 19 | -------------------------------------------------------------------------------- /March/29mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxSatisfaction(int[] satisfaction) { 3 | int ans = 0; 4 | int sumSatisfaction = 0; 5 | 6 | satisfaction = Arrays.stream(satisfaction) 7 | .boxed() 8 | .sorted(Collections.reverseOrder()) 9 | .mapToInt(Integer::intValue) 10 | .toArray(); 11 | 12 | for (final int s : satisfaction) { 13 | sumSatisfaction += s; 14 | if (sumSatisfaction <= 0) 15 | return ans; 16 | ans += sumSatisfaction; 17 | } 18 | 19 | return ans; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /March/30mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isScramble(String s1, String s2) { 3 | if (s1.equals(s2)) 4 | return true; 5 | final String hashKey = s1 + "+" + s2; 6 | if (memo.containsKey(hashKey)) 7 | return memo.get(hashKey); 8 | 9 | int[] count = new int[128]; 10 | 11 | for (int i = 0; i < s1.length(); ++i) { 12 | ++count[s1.charAt(i)]; 13 | --count[s2.charAt(i)]; 14 | } 15 | 16 | for (final int c : count) 17 | if (c != 0) { 18 | memo.put(hashKey, false); 19 | return false; 20 | } 21 | 22 | for (int i = 1; i < s1.length(); ++i) { 23 | if (isScramble(s1.substring(0, i), s2.substring(0, i)) && 24 | isScramble(s1.substring(i), s2.substring(i))) { 25 | memo.put(hashKey, true); 26 | return true; 27 | } 28 | if (isScramble(s1.substring(0, i), s2.substring(s2.length() - i)) && 29 | isScramble(s1.substring(i), s2.substring(0, s2.length() - i))) { 30 | memo.put(hashKey, true); 31 | return true; 32 | } 33 | } 34 | 35 | memo.put(hashKey, false); 36 | return false; 37 | } 38 | 39 | private Map memo = new HashMap<>(); 40 | } 41 | -------------------------------------------------------------------------------- /March/31mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int ways(String[] pizza, int k) { 3 | final int M = pizza.length; 4 | final int N = pizza[0].length(); 5 | // dp[m][n][k] := # of ways to cut pizza[m:M][n:N] w/ k cuts 6 | dp = new int[M][N][k]; 7 | for (int[][] A : dp) 8 | Arrays.stream(A).forEach(a -> Arrays.fill(a, -1)); 9 | prefix = new int[M + 1][N + 1]; 10 | 11 | for (int i = 0; i < M; ++i) 12 | for (int j = 0; j < N; ++j) 13 | prefix[i + 1][j + 1] = (pizza[i].charAt(j) == 'A' ? 1 : 0) + prefix[i][j + 1] + 14 | prefix[i + 1][j] - prefix[i][j]; 15 | 16 | return ways(0, 0, k - 1, M, N); 17 | } 18 | 19 | private static final int kMod = 1_000_000_007; 20 | private int[][][] dp; 21 | private int[][] prefix; 22 | 23 | // HasApple of pizza[row1..row2)[col1..col2) 24 | private boolean hasApple(int row1, int row2, int col1, int col2) { 25 | return (prefix[row2][col2] - prefix[row1][col2] - prefix[row2][col1] + prefix[row1][col1]) > 0; 26 | } 27 | 28 | private int ways(int m, int n, int k, final int M, final int N) { 29 | if (k == 0) 30 | return 1; 31 | if (dp[m][n][k] >= 0) 32 | return dp[m][n][k]; 33 | 34 | dp[m][n][k] = 0; 35 | 36 | for (int i = m + 1; i < M; ++i) // Cut horizontally 37 | if (hasApple(m, i, n, N) && hasApple(i, M, n, N)) 38 | dp[m][n][k] = (dp[m][n][k] + ways(i, n, k - 1, M, N)) % kMod; 39 | 40 | for (int j = n + 1; j < N; ++j) // Cut vertically 41 | if (hasApple(m, M, n, j) && hasApple(m, M, j, N)) 42 | dp[m][n][k] = (dp[m][n][k] + ways(m, j, k - 1, M, N)) % kMod; 43 | 44 | return dp[m][n][k]; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /March/5mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minJumps(int[] arr) { 3 | final int n = arr.length; 4 | // {a: indices} 5 | Map> graph = new HashMap<>(); 6 | Queue q = new ArrayDeque<>(Arrays.asList(0)); 7 | boolean[] seen = new boolean[n]; 8 | seen[0] = true; 9 | 10 | for (int i = 0; i < n; ++i) { 11 | graph.putIfAbsent(arr[i], new ArrayList<>()); 12 | graph.get(arr[i]).add(i); 13 | } 14 | 15 | for (int steps = 0; !q.isEmpty(); ++steps) { 16 | for (int sz = q.size(); sz > 0; --sz) { 17 | final int i = q.poll(); 18 | if (i == n - 1) 19 | return steps; 20 | seen[i] = true; 21 | final int u = arr[i]; 22 | if (i + 1 < n) 23 | graph.get(u).add(i + 1); 24 | if (i - 1 >= 0) 25 | graph.get(u).add(i - 1); 26 | for (final int v : graph.get(u)) { 27 | if (seen[v]) 28 | continue; 29 | q.offer(v); 30 | } 31 | graph.get(u).clear(); 32 | } 33 | } 34 | 35 | throw new IllegalArgumentException(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /March/6mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findKthPositive(int[] arr, int k) { 3 | int l = 0; 4 | int r = arr.length; 5 | 6 | // Find the first index l s.t. nMissing(l) = A[l] - l - 1 >= k 7 | while (l < r) { 8 | final int m = (l + r) / 2; 9 | if (arr[m] - m - 1 >= k) 10 | r = m; 11 | else 12 | l = m + 1; 13 | } 14 | 15 | // The k-th missing positive 16 | // = A[l - 1] + k - nMissing(l - 1) 17 | // = A[l - 1] + k - (A[l - 1] - (l - 1) - 1) 18 | // = A[l - 1] + k - (A[l - 1] - l) 19 | // = l + k 20 | return l + k; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /March/7mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long minimumTime(int[] time, int totalTrips) { 3 | long l = 1; 4 | long r = Arrays.stream(time).min().getAsInt() * (long) totalTrips; 5 | 6 | while (l < r) { 7 | final long m = (l + r) / 2; 8 | if (numTrips(time, m) >= totalTrips) 9 | r = m; 10 | else 11 | l = m + 1; 12 | } 13 | 14 | return l; 15 | } 16 | 17 | private long numTrips(int[] time, long m) { 18 | return Arrays.stream(time).asLongStream().reduce(0L, (subtotal, t) -> subtotal + m / t); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /March/8mar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minEatingSpeed(int[] piles, int h) { 3 | int l = 1; 4 | int r = Arrays.stream(piles).max().getAsInt(); 5 | 6 | while (l < r) { 7 | final int m = (l + r) / 2; 8 | if (eatHours(piles, m) <= h) 9 | r = m; 10 | else 11 | l = m + 1; 12 | } 13 | 14 | return l; 15 | } 16 | 17 | // hours to eat all piles with speed m 18 | private int eatHours(int[] piles, int m) { 19 | return Arrays.stream(piles).reduce( 20 | 0, (subtotal, pile) -> subtotal + (pile - 1) / m + 1); // Math.ceil(pile / m) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /March/9mar.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ListNode detectCycle(ListNode head) { 3 | ListNode slow = head; 4 | ListNode fast = head; 5 | 6 | while (fast != null && fast.next != null) { 7 | slow = slow.next; 8 | fast = fast.next.next; 9 | if (slow == fast) { 10 | slow = head; 11 | while (slow != fast) { 12 | slow = slow.next; 13 | fast = fast.next; 14 | } 15 | return slow; 16 | } 17 | } 18 | 19 | return null; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Pattern - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 2 | ## Medium 3 |

Geek is very fond of patterns. Once, his teacher gave him a star pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek to build a star pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |

12 | 
13 | 
14 | 15 |

Your Task:

16 | 17 |

You don't need to input anything. Complete the function printDiamond() which takes  an integer n  as the input parameter and print the pattern.

18 | 19 |

Constraints:

20 | 21 |
    22 |
  • 1<= N <= 20
  • 23 |
24 | 25 |

 

26 |
-------------------------------------------------------------------------------- /Pattern - GFG/pattern.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | void printDiamond(int n) { 10 | // code here 11 | 12 | 13 | for ( int i=0; i> t; 43 | while (t--) { 44 | int n; 45 | cin >> n; 46 | 47 | Solution ob; 48 | ob.printDiamond(n); 49 | } 50 | return 0; 51 | } 52 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 1 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 1 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a square pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek to build a star pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |
Input: 5
12 |
13 | Output:
14 | * * * * *
15 | * * * * *
16 | * * * * *
17 | * * * * *
18 | * * * * *
19 | 20 |

 

21 | 22 |

Your Task:

23 | 24 |

You don't need to input anything. Complete the function printSquare() which takes  an integer n  as the input parameter and print the pattern.

25 | 26 |

Constraints:

27 | 28 |
    29 |
  • 1<= N <= 20
  • 30 |
31 |
-------------------------------------------------------------------------------- /Pattern 1 - GFG/pattern-1.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | void printSquare(int n) { 10 | // code here 11 | for( int i=0; i> t; 25 | while (t--) { 26 | int n; 27 | cin >> n; 28 | 29 | Solution ob; 30 | ob.printSquare(n); 31 | } 32 | return 0; 33 | } 34 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 11 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 11 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek to build a star pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |
Input: 5
12 | 
13 | Output:
14 | 1 
15 | 0 1 
16 | 1 0 1
17 | 0 1 0 1 
18 | 1 0 1 0 1
19 | 20 |

 

21 | 22 |

Your Task:

23 | 24 |

You don't need to input anything. Complete the function printTriangle() which takes  an integer n  as the input parameter and print the pattern.

25 | 26 |

Constraints:

27 | 28 |
    29 |
  • 1<= N <= 20
  • 30 |
31 |
-------------------------------------------------------------------------------- /Pattern 11 - GFG/pattern-11.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | void printTriangle(int n) { 10 | // code here 11 | int start=1; 12 | for (int i=0; i> t; 33 | while (t--) { 34 | int n; 35 | cin >> n; 36 | 37 | Solution ob; 38 | ob.printTriangle(n); 39 | } 40 | return 0; 41 | } 42 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 12 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 12 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek to build the pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |
Input: 5
12 | 
13 | Output:
14 | 1                 1
15 | 1 2             2 1
16 | 1 2 3         3 2 1
17 | 1 2 3 4     4 3 2 1
18 | 1 2 3 4 5 5 4 3 2 1
19 | 20 |

 

21 | 22 |

Your Task:

23 | 24 |

You don't need to input anything. Complete the function printTriangle() which takes  an integer n  as the input parameter and print the pattern.

25 | 26 |

Constraints:

27 | 28 |
    29 |
  • 1<= N <= 20
  • 30 |
31 |
-------------------------------------------------------------------------------- /Pattern 12 - GFG/pattern-12.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | void printTriangle(int n) { 10 | // code here 11 | for ( int i=1; i<=n; i++) { 12 | for ( int j=1; j<=i; j++) { 13 | cout<=1; j--){ 21 | cout<> t; 37 | while (t--) { 38 | int n; 39 | cin >> n; 40 | 41 | Solution ob; 42 | ob.printTriangle(n); 43 | } 44 | return 0; 45 | } 46 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 13 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 13 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek to build the pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |
Input: 5
12 | 
13 | Output:
14 | 1 
15 | 2 3 
16 | 4 5 6 
17 | 7 8 9 10 
18 | 11 12 13 14 15
19 | 20 |

 

21 | 22 |

Your Task:

23 | 24 |

You don't need to input anything. Complete the function printTriangle() which takes  an integer n  as the input parameter and print the pattern.

25 | 26 |

Constraints:

27 | 28 |
    29 |
  • 1<= N <= 20
  • 30 |
31 |
-------------------------------------------------------------------------------- /Pattern 13 - GFG/pattern-13.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | void printTriangle(int n) { 10 | // code here 11 | int num=1; 12 | for ( int i=0; i> t; 28 | while (t--) { 29 | int n; 30 | cin >> n; 31 | 32 | Solution ob; 33 | ob.printTriangle(n); 34 | } 35 | return 0; 36 | } 37 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 14 - GFG/pattern-14.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | void printTriangle(int n) { 10 | // code here 11 | for ( int i=0; i> t; 27 | while (t--) { 28 | int n; 29 | cin >> n; 30 | 31 | Solution ob; 32 | ob.printTriangle(n); 33 | } 34 | return 0; 35 | } 36 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 15 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 15 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek to build the pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |
Input: 5
12 | 
13 | Output:
14 | ABCDE
15 | ABCD
16 | ABC
17 | AB
18 | A
19 | 
20 | 21 |

 

22 | 23 |

Your Task:

24 | 25 |

You don't need to input anything. Complete the function printTriangle() which takes  an integer n  as the input parameter and print the pattern.

26 | 27 |

Constraints:

28 | 29 |
    30 |
  • 1<= N <= 20
  • 31 |
32 |
-------------------------------------------------------------------------------- /Pattern 15 - GFG/pattern-15.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | void printTriangle(int n) { 10 | // code here 11 | for ( int i=0; i> t; 25 | while (t--) { 26 | int n; 27 | cin >> n; 28 | 29 | Solution ob; 30 | ob.printTriangle(n); 31 | } 32 | return 0; 33 | } 34 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 16 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 16 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek to build the pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |
Input: 5
12 | 
13 | Output:
14 | A
15 | BB
16 | CCC
17 | DDDD
18 | EEEEE
19 | 
20 | 
21 | 
22 | 23 |

Your Task:

24 | 25 |

You don't need to input anything. Complete the function printTriangle() which takes  an integer n  as the input parameter and print the pattern.

26 | 27 |

Constraints:

28 | 29 |
    30 |
  • 1<= N <= 20
  • 31 |
32 |
-------------------------------------------------------------------------------- /Pattern 16 - GFG/pattern-16.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | void printTriangle(int n) { 10 | // code here 11 | for ( int i=0; i> t; 28 | while (t--) { 29 | int n; 30 | cin >> n; 31 | 32 | Solution ob; 33 | ob.printTriangle(n); 34 | } 35 | return 0; 36 | } 37 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 17 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 17 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek to build the pattern.

6 | 7 |

Example 1:

8 | 9 |
Input: 4
10 | Output:
11 |    A
12 |   ABA
13 |  ABCBA
14 | ABCDCBA
15 | 16 |

Your Task:

17 | 18 |

You don't need to input anything. Complete the function printTriangle() which takes an integer n  as the input parameter and prints the pattern.

19 | 20 |

Constraints:

21 | 22 |
    23 |
  • 1<= N <= 20
  • 24 |
25 |
-------------------------------------------------------------------------------- /Pattern 17 - GFG/pattern-17.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | void printTriangle(int n) { 10 | // code here 11 | for ( int i=0; i> t; 40 | while (t--) { 41 | int n; 42 | cin >> n; 43 | 44 | Solution ob; 45 | ob.printTriangle(n); 46 | } 47 | return 0; 48 | } 49 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 2 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 2 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek to build a star pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |

Input: 5
12 |
13 | Output:
14 | * 
15 | * * 
16 | * * * 
17 | * * * * 
18 | * * * * *

19 | 20 |

 

21 | 22 |

Your Task:

23 | 24 |

You don't need to input anything. Complete the function printTriangle() which takes  an integer n  as the input parameter and print the pattern.

25 | 26 |

Constraints:

27 | 28 |
    29 |
  • 1<= N <= 20
  • 30 |
31 |
-------------------------------------------------------------------------------- /Pattern 2 - GFG/pattern-2.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | void printTriangle(int n) { 10 | // code here 11 | for ( int i =0; i> t; 25 | while (t--) { 26 | int n; 27 | cin >> n; 28 | 29 | Solution ob; 30 | ob.printTriangle(n); 31 | } 32 | return 0; 33 | } 34 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 3 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 3 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a  pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek to build a pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |

Input: 5
12 |
13 | Output:
14 | 1
15 | 1 2 
16 | 1 2 3 
17 | 1 2 3 4 
18 | 1 2 3 4 5

19 | 20 |

 

21 | 22 |

Your Task:

23 | 24 |

You don't need to input anything. Complete the function printTriangle() which takes  an integer n  as the input parameter and print the pattern.

25 | 26 |

Constraints:

27 | 28 |
    29 |
  • 1<= N <= 20
  • 30 |
31 |
-------------------------------------------------------------------------------- /Pattern 3 - GFG/pattern-3.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | void printTriangle(int n) { 10 | // code here 11 | for ( int i=0; i> t; 25 | while (t--) { 26 | int n; 27 | cin >> n; 28 | 29 | Solution ob; 30 | ob.printTriangle(n); 31 | } 32 | return 0; 33 | } 34 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 4 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 4 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a  pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek to build a pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |

Input: 5
12 |
13 | Output:
14 | 1
15 | 2 2 
16 | 3 3 3 
17 | 4 4 4 4 
18 | 5 5 5 5 5

19 | 20 |

 

21 | 22 |

Your Task:

23 | 24 |

You don't need to input anything. Complete the function printTriangle() which takes  an integer n  as the input parameter and print the pattern.

25 | 26 |

Constraints:

27 | 28 |
    29 |
  • 1<= N <= 20
  • 30 |
31 |
-------------------------------------------------------------------------------- /Pattern 4 - GFG/pattern-4.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | void printTriangle(int n) { 10 | // code here 11 | for ( int i=0; i> t; 25 | while (t--) { 26 | int n; 27 | cin >> n; 28 | 29 | Solution ob; 30 | ob.printTriangle(n); 31 | } 32 | return 0; 33 | } 34 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 5 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 5 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek build a star pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |

Input: 5
12 |
13 | Output:
14 | * * * * *
15 | * * * * 
16 | * * * 
17 | * *  
18 | * 

19 | 20 |

 

21 | 22 |

Your Task:

23 | 24 |

You don't need to input anything. Complete the function printTriangle() which takes  an integer n  as the input parameter and print the pattern.

25 | 26 |

Constraints:

27 | 28 |
    29 |
  • 1<= N <= 20
  • 30 |
31 |
-------------------------------------------------------------------------------- /Pattern 5 - GFG/pattern-5.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution{ 8 | public: 9 | 10 | void printTriangle(int n) { 11 | // code here 12 | for(int i=0; i> t; 26 | while (t--) { 27 | int n; 28 | cin >> n; 29 | 30 | Solution ob; 31 | ob.printTriangle(n); 32 | } 33 | return 0; 34 | } 35 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 6 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 6 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a  pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek to build a pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |

Input: 5
12 |
13 | Output:
14 | 1 2 3 4 5
15 | 1 2 3 4
16 | 1 2 3 
17 | 1 2  
18 | 1 

19 | 20 |

 

21 | 22 |

Your Task:

23 | 24 |

You don't need to input anything. Complete the function printTriangle() which takes  an integer n  as the input parameter and print the pattern.

25 | 26 |

Constraints:

27 | 28 |
    29 |
  • 1<= N <= 20
  • 30 |
31 |
-------------------------------------------------------------------------------- /Pattern 6 - GFG/pattern-6.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution{ 8 | public: 9 | 10 | void printTriangle(int n) { 11 | // code here 12 | for(int i=0; i> t; 26 | while (t--) { 27 | int n; 28 | cin >> n; 29 | 30 | Solution ob; 31 | ob.printTriangle(n); 32 | } 33 | return 0; 34 | } 35 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 7 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 7 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a  pattern to solve. He gave Ram an integer n and asked him to build a pattern.

4 | 5 |

Help Ram build a pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |
Input: 5
12 | 
13 | Output:
14 |     *
15 |    ***  
16 |   *****
17 |  *******
18 | *********
19 | Your Task:
20 | 21 |

You don't need to input anything. Complete the function printTriangle() which takes  an integer n  as the input parameter and print the pattern.

22 | 23 |

Constraints:

24 | 25 |
    26 |
  • 1<= N <= 20
  • 27 |
28 |
-------------------------------------------------------------------------------- /Pattern 7 - GFG/pattern-7.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | void printTriangle(int n) { 10 | // code here 11 | for ( int i=0; i> t; 28 | while (t--) { 29 | int n; 30 | cin >> n; 31 | 32 | Solution ob; 33 | ob.printTriangle(n); 34 | } 35 | return 0; 36 | } 37 | // } Driver Code Ends -------------------------------------------------------------------------------- /Pattern 8 - GFG/README.md: -------------------------------------------------------------------------------- 1 | # Pattern 8 2 | ## Easy 3 |

Geek is very fond of patterns. Once, his teacher gave him a  pattern to solve. He gave Geek an integer n and asked him to build a pattern.

4 | 5 |

Help Geek to build a pattern.

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |
Input: 5
12 | 
13 | Output:
14 | 
15 | *********
16 |  *******
17 |   *****
18 |    ***
19 |     *
20 | 
21 | 
22 | 23 |

Your Task:

24 | 25 |

You don't need to input anything. Complete the function printTriangle() which takes  an integer n  as the input parameter and print the pattern.

26 | 27 |

Constraints:

28 | 29 |
    30 |
  • 1<= N <= 20
  • 31 |
32 |
-------------------------------------------------------------------------------- /Pattern 8 - GFG/pattern-8.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | class Solution{ 8 | public: 9 | 10 | void printTriangle(int n) { 11 | // code here 12 | for ( int i=0; i> t; 31 | while (t--) { 32 | int n; 33 | cin >> n; 34 | 35 | Solution ob; 36 | ob.printTriangle(n); 37 | } 38 | return 0; 39 | } 40 | // } Driver Code Ends -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Leetcode-daily-solution 2 | Collection of LeetCode questions to ace the coding interview! - Created using [LeetHub](https://github.com/QasimWani/LeetHub)
3 | contains solutions in java & c++
4 |
5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | -------------------------------------------------------------------------------- /Study plans/leetcode 75/72. Edit Distance.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minDistance(String word1, String word2) { 3 | final int m = word1.length(); 4 | final int n = word2.length(); 5 | // dp[i][j] := min # of operations to convert word1[0..i) to word2[0..j) 6 | int[][] dp = new int[m + 1][n + 1]; 7 | 8 | for (int i = 1; i <= m; ++i) 9 | dp[i][0] = i; 10 | 11 | for (int j = 1; j <= n; ++j) 12 | dp[0][j] = j; 13 | 14 | for (int i = 1; i <= m; ++i) 15 | for (int j = 1; j <= n; ++j) 16 | if (word1.charAt(i - 1) == word2.charAt(j - 1)) 17 | dp[i][j] = dp[i - 1][j - 1]; 18 | else 19 | dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1; 20 | 21 | return dp[m][n]; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /day1.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool wordPattern(string pattern, string str) { 4 | const int n = pattern.length(); 5 | istringstream iss(str); 6 | vector charToIndex(128); 7 | unordered_map stringToIndex; 8 | 9 | int i = 0; 10 | for (string word; iss >> word; ++i) { 11 | if (i == n) // Out of bound 12 | return false; 13 | if (charToIndex[pattern[i]] != stringToIndex[word]) 14 | return false; 15 | charToIndex[pattern[i]] = i + 1; 16 | stringToIndex[word] = i + 1; 17 | } 18 | 19 | return i == n; 20 | } 21 | }; -------------------------------------------------------------------------------- /day10.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSameTree(TreeNode* p, TreeNode* q) { 4 | if(p == NULL && q == NULL){ 5 | return true; 6 | }else if(p != NULL && q == NULL){ 7 | return false; 8 | }else if(p == NULL && q != NULL){ 9 | return false; 10 | } 11 | 12 | return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 13 | } 14 | }; -------------------------------------------------------------------------------- /day11.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool dfs(int node, vector& hasApple, vector adj[], int &time, vector &vis){ 5 | if(adj[node].empty()) return (hasApple[node] == true); 6 | 7 | vis[node]=1; 8 | 9 | bool curr = false; 10 | 11 | for(auto x : adj[node]){ 12 | time += 2; 13 | bool check = false; 14 | if(vis[x] == false){ 15 | check = dfs(x,hasApple,adj,time,vis); 16 | } 17 | if(!check) time -= 2; 18 | else curr=true; 19 | 20 | } 21 | 22 | return (curr || (hasApple[node] == true)); 23 | } 24 | int minTime(int n, vector>& edges, vector& hasApple) { 25 | vector adj[n]; 26 | for(auto x : edges){ 27 | adj[x[0]].push_back(x[1]); 28 | adj[x[1]].push_back(x[0]); 29 | } 30 | vector vis(n,false); 31 | int time=0; 32 | dfs(0,hasApple,adj,time,vis); 33 | return time; 34 | } 35 | }; -------------------------------------------------------------------------------- /day12.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector dfs(vector>& adjList, string& labels, int parent, int cur, vector& ans){ 4 | vector counter(26, 0); 5 | char c = labels[cur]-'a'; 6 | counter[c] = 1; 7 | 8 | for(int nei : adjList[cur]){ 9 | if(nei != parent){ 10 | vector subcounter = dfs(adjList, labels, cur, nei, ans); 11 | for(int i = 0; i < counter.size(); ++i){ 12 | counter[i] += subcounter[i]; 13 | } 14 | } 15 | } 16 | //since we are using dfs, now counter's coverage is the subtree rooted at cur 17 | ans[cur] = counter[c]; 18 | 19 | return counter; 20 | }; 21 | 22 | vector countSubTrees(int n, vector>& edges, string labels) { 23 | vector> adjList(n); 24 | vector> counter(n, vector(26, -1)); 25 | 26 | //bi-directional 27 | for(vector& edge : edges){ 28 | adjList[edge[0]].push_back(edge[1]); 29 | adjList[edge[1]].push_back(edge[0]); 30 | } 31 | 32 | vector ans(n, 0); 33 | int parent = -1; 34 | 35 | dfs(adjList, labels, -1, 0, ans); 36 | 37 | return ans; 38 | } 39 | };; -------------------------------------------------------------------------------- /day13.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestPath(vector& parent, string s) { 4 | const int n = parent.size(); 5 | int ans = 1; 6 | vector> graph(n); 7 | 8 | for (int i = 1; i < n; ++i) 9 | graph[parent[i]].push_back(i); 10 | 11 | longestPathDownFrom(graph, 0, s, ans); 12 | return ans; 13 | } 14 | 15 | private: 16 | int longestPathDownFrom(const vector>& graph, int u, 17 | const string& s, int& ans) { 18 | int max1 = 0; 19 | int max2 = 0; 20 | 21 | for (const int v : graph[u]) { 22 | const int res = longestPathDownFrom(graph, v, s, ans); 23 | if (s[u] == s[v]) 24 | continue; 25 | if (res > max1) { 26 | max2 = max1; 27 | max1 = res; 28 | } else if (res > max2) { 29 | max2 = res; 30 | } 31 | } 32 | 33 | ans = max(ans, 1 + max1 + max2); 34 | return 1 + max1; 35 | } 36 | }; -------------------------------------------------------------------------------- /day14.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char dfs(char c, vector& unionGraph) { 4 | if(unionGraph[c] != '\0') return dfs(unionGraph[c], unionGraph); 5 | return c; 6 | } 7 | void merge(char big, char small, vector& unionGraph) { 8 | if(big=='\0' || small == '\0') return; 9 | if(unionGraph[big] > small) { 10 | // cout< unionGraph(200, '\0'); 22 | for(int i = 0; i < s1.size(); i ++) { 23 | char big = max(s1[i], s2[i]); 24 | char small = min(s1[i], s2[i]); 25 | if(big != small) merge(big, small, unionGraph); 26 | } 27 | string res = ""; 28 | for(auto &ch: baseStr) { 29 | res += dfs(ch, unionGraph); 30 | } 31 | return res; 32 | } 33 | }; -------------------------------------------------------------------------------- /day15.c++: -------------------------------------------------------------------------------- 1 | class UnionFind { 2 | public: 3 | UnionFind(int n) : id(n), rank(n) { 4 | iota(begin(id), end(id), 0); 5 | } 6 | 7 | void unionByRank(int u, int v) { 8 | const int i = find(u); 9 | const int j = find(v); 10 | if (i == j) 11 | return; 12 | if (rank[i] < rank[j]) { 13 | id[i] = id[j]; 14 | } else if (rank[i] > rank[j]) { 15 | id[j] = id[i]; 16 | } else { 17 | id[i] = id[j]; 18 | ++rank[j]; 19 | } 20 | } 21 | 22 | int find(int u) { 23 | return id[u] == u ? u : id[u] = find(id[u]); 24 | } 25 | 26 | private: 27 | vector id; 28 | vector rank; 29 | }; 30 | 31 | class Solution { 32 | public: 33 | int numberOfGoodPaths(vector& vals, vector>& edges) { 34 | const int n = vals.size(); 35 | int ans = n; 36 | UnionFind uf(n); 37 | vector> graph(n); 38 | map> valToNodes; 39 | 40 | for (int i = 0; i < vals.size(); ++i) 41 | valToNodes[vals[i]].push_back(i); 42 | 43 | for (const vector& edge : edges) { 44 | const int u = edge[0]; 45 | const int v = edge[1]; 46 | if (vals[v] <= vals[u]) 47 | graph[u].push_back(v); 48 | if (vals[u] <= vals[v]) 49 | graph[v].push_back(u); 50 | } 51 | 52 | for (const auto& [val, nodes] : valToNodes) { 53 | for (const int u : nodes) 54 | for (const int v : graph[u]) 55 | uf.unionByRank(u, v); 56 | unordered_map rootCount; 57 | for (const int u : nodes) 58 | ++rootCount[uf.find(u)]; 59 | // For each group, C(count, 2) := count * (count - 1) / 2 60 | for (const auto& [_, count] : rootCount) 61 | ans += count * (count - 1) / 2; 62 | } 63 | 64 | return ans; 65 | } 66 | }; -------------------------------------------------------------------------------- /day16.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> insert(vector>& intervals, vector& newInterval) { 4 | vector> ans; 5 | int i = 0, n = intervals.size(); 6 | 7 | //smaller, no intersection 8 | while(i < n && intervals[i][1] < newInterval[0]){ 9 | ans.push_back(intervals[i]); 10 | ++i; 11 | } 12 | 13 | //having intersection 14 | int start = newInterval[0], end = newInterval[1]; 15 | while(i < n && intervals[i][0] <= end){ 16 | start = min(intervals[i][0], start); 17 | end = max(intervals[i][1], end); 18 | ++i; 19 | } 20 | 21 | ans.push_back({start, end}); 22 | 23 | while(i < n){ 24 | ans.push_back(intervals[i]); 25 | ++i; 26 | } 27 | 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /day17.c++: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minFlipsMonoIncr(string S) 5 | { 6 | int count_flip = 0, count_one = 0; 7 | for (auto i : S) 8 | { 9 | if (i == '1') 10 | count_one++; 11 | else 12 | count_flip++; 13 | count_flip = min(count_flip, count_one); 14 | } 15 | return count_flip; 16 | } 17 | }; -------------------------------------------------------------------------------- /day18.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubarraySumCircular(vector& A) { 4 | int total_sum=0,curr_sum1=0,curr_sum2=0,mxsum_subary=INT_MIN,minsum_subary=INT_MAX; 5 | for(auto i:A) 6 | { 7 | total_sum+=i; curr_sum1+=i; curr_sum2+=i; 8 | mxsum_subary=max(mxsum_subary,curr_sum1); 9 | if(curr_sum1<0) curr_sum1=0; 10 | minsum_subary=min(curr_sum2,minsum_subary); 11 | if(curr_sum2>0) curr_sum2=0; 12 | } 13 | return (total_sum==minsum_subary)?mxsum_subary:max(mxsum_subary,total_sum-minsum_subary); 14 | } 15 | }; -------------------------------------------------------------------------------- /day19.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | //This function return the mod of negative and positive integer with k; 4 | //In c++ when we have neg number mod k then we get that negative number so 5 | //to make all the number positive and less than k we are taking mod with k. 6 | int negMod(int n,int mod){ 7 | 8 | if(n<0){//if our number is negative 9 | n=abs(n)%mod; 10 | return (-n+mod)%mod; 11 | } 12 | //if our number is postive 13 | return n%mod; 14 | } 15 | int subarraysDivByK(vector& nums, int k) { 16 | int n=nums.size(); 17 | //now we are having two variables cur and ans in cur variable we are 18 | //storing the cur sum mod k 19 | //in ans we are storing the occurance of subarray which is divisible by k 20 | int cur=0,ans=0; 21 | unordered_mapm; 22 | //initially our cur sum is empty so we have make our map of 0 to increase to 1. 23 | m[0]++; 24 | 25 | for(int num:nums){ 26 | 27 | cur=(cur+negMod(num,k))%k;//adding the mod value to cur 28 | 29 | if(m.count(cur)){//if we have cur number in the map so there must be an subarray 30 | //between them with sum =0 31 | ans+=m[cur]; 32 | 33 | } 34 | //incrementing the cur value 35 | m[cur]++; 36 | } 37 | //return the ans 38 | return ans; 39 | } 40 | }; -------------------------------------------------------------------------------- /day2.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool detectCapitalUse(string word) { 4 | for (int i = 1; i < word.length(); ++i) 5 | if (isupper(word[1]) != isupper(word[i]) || 6 | islower(word[0]) && isupper(word[i])) 7 | return false; 8 | return true; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /day20.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void func(int idx,vector&nums,vector&a,set>&ans){ 4 | int n=nums.size(); 5 | //If we have our index greater than or equal to sizeof nums then we cant go further 6 | //so we will check if there is a subarray with size greater than equal to 2 7 | if(idx>=n){ 8 | if(a.size()>=2){ 9 | //if we have such subarray we will insert it to the set 10 | ans.insert(a); 11 | } 12 | return ; 13 | } 14 | //now for [0,n-1] index we will check either condition for inserting into a vector 15 | //1. if a vector is empty so we can push the element easily 16 | //2. if a last element is less than equal to cur element 17 | if(!a.size()||nums[idx]>=a.back()){ 18 | //we will push back into a vector and then call the func for idx+1; 19 | a.push_back(nums[idx]); 20 | func(idx+1,nums,a,ans); 21 | //we are removing element because a vector is being passed by reference 22 | a.pop_back(); 23 | } 24 | //calling the function without that value 25 | func(idx+1,nums,a,ans); 26 | } 27 | vector> findSubsequences(vector& nums) { 28 | //we have made a temp vector for storing the values till an index 29 | vectortemp; 30 | //we have made a set of vector because there can be repeated elements which cause 31 | //repetion of subarray so set doesnt allow repetion of values 32 | set>ans; 33 | //we are calling our recursive function giving starting index to 0 34 | func(0,nums,temp,ans); 35 | //typecasting the set into vector and returning it we can do it manually also 36 | return vector(ans.begin(),ans.end()); 37 | 38 | } 39 | }; -------------------------------------------------------------------------------- /day21.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool check(string s){ 4 | int n=s.size(); 5 | //if the size of string is 1 that is always possible so return true 6 | if(n==1){ 7 | return true; 8 | } 9 | //if we have length >3 or string starts with 0 return false 10 | if(n>3||s[0]=='0'){ 11 | return false; 12 | } 13 | //we are converting string to integer to check if it is less than equalto 255 14 | int val=stoi(s); 15 | if(val>255){ 16 | return false; 17 | } 18 | //return true at last 19 | return true; 20 | } 21 | vector restoreIpAddresses(string s) { 22 | int n=s.size(); 23 | //we will store our ans in ans vector of strings 24 | vectorans; 25 | //the max length of the ip address could be 12 as 255.255.255.255 so 26 | //all the string s with size greater than 12 can have ans 27 | if(n>12){ 28 | return ans; 29 | } 30 | //now we have our string of length 12 or less than 12 so now 31 | //1. we have to spit the s in parts such that it satisfy the ip address conditions 32 | //2. if all 4 strings satisfy the condition we will push into ans vector 33 | 34 | for(int i=1;i<=3;i++){//for the length before first '.' 35 | for(int j=1;j<=3;j++){//for the length between first and second '.' 36 | for(int k=1;k<=3;k++){//for the length between second and third '.' 37 | //checking condition if the last segment is of length 3 or less 38 | if(i+j+k=n){ 39 | //dividing the s int substrings 40 | string a=s.substr(0,i); 41 | string b=s.substr(i,j); 42 | string c=s.substr(j+i,k); 43 | string d=s.substr(i+j+k); 44 | //if all the substring satisfy the check function condition 45 | //then we will push into ans vector 46 | if(check(a)&&check(b)&&check(c)&&check(d)){ 47 | ans.push_back(a+"."+b+"."+c+"."+d); 48 | } 49 | } 50 | } 51 | } 52 | } 53 | //return the ans vector 54 | return ans; 55 | } 56 | }; -------------------------------------------------------------------------------- /day22.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool ispalindrome(string s,int start,int last){ 5 | while(start<=last){ 6 | if(s[start++]!=s[last--]){ 7 | return false; 8 | } 9 | 10 | } 11 | return true; 12 | } 13 | 14 | void solve(vector> &ans,string s,vector &path,int idx,int n){ 15 | 16 | if(idx==n){ 17 | ans.push_back(path); 18 | return; 19 | } 20 | 21 | for(int i=idx;i> partition(string s) { 32 | vector> ans; 33 | vector path; 34 | int n = s.size(); 35 | solve(ans,s,path,0,n); 36 | return ans; 37 | } 38 | }; -------------------------------------------------------------------------------- /day23.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findJudge(int n, vector>& trust) { 4 | 5 | //Initialized vectors of size n+1 with 0 to be able to store values for index 1 to n 6 | vector trusting(n+1,0); 7 | vector trusted(n+1,0); 8 | 9 | for(int i=0;i& edges, vector& distance, vector& visited){ 4 | visited[node] = true; 5 | int neighbor = edges[node]; 6 | if (neighbor != -1 && visited[neighbor] == false) { 7 | distance[neighbor] = distance[node] + 1; 8 | dfs(neighbor, edges, distance, visited); 9 | } 10 | } 11 | //we are using DFS to solve this problem 12 | int closestMeetingNode(vector& edges, int node1, int node2) { 13 | int n = edges.size(); 14 | int ans = -1; 15 | int minDist = INT_MAX; 16 | //dist1 store the distance from node1 to all the neighbour nodes and dist2 store the distance from node2 to all the neighbour nodes 17 | vector dist1(n, 0), dist2(n, 0); 18 | //visited array helps us to identify wheather we visited to particular node form node1 or not similarly for visited2 19 | vector visited1(n, false), visited2(n, false); 20 | //calling dfs from both the nodes i.e. node1 and node2 21 | dfs(node1, edges, dist1, visited1); 22 | dfs(node2, edges, dist2, visited2); 23 | 24 | for(int currNode = 0; currNode < n; currNode++){ 25 | if(visited1[currNode] == true && visited2[currNode] == true && minDist > max(dist1[currNode], dist2[currNode])){ 26 | minDist = max(dist1[currNode], dist2[currNode]); 27 | ans = currNode; 28 | } 29 | } 30 | return ans; 31 | } 32 | }; -------------------------------------------------------------------------------- /day26.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | template 5 | void bellman_ford(T_a3 &g, T_vector &dist, int src, int mx_edges) { 6 | dist[src] = 0; 7 | for (int i = 0; i <= mx_edges; i++) { 8 | T_vector ndist = dist; 9 | for (auto x : g) { 10 | auto [from, to, cost] = x; 11 | ndist[to] = min(ndist[to], dist[from] + cost); 12 | } 13 | dist = ndist; 14 | } 15 | } 16 | 17 | int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { 18 | // we can directly use bellman ford template here (prerequisite: you need to understand bellman ford algo) 19 | // bellman ford algo is used to find the shortest paths from source node to other nodes in a weighted graph 20 | vector> g; 21 | // initially cost with a large value 22 | // cost[i] means the cheapest price from src to city i 23 | vector cost(n, 1e9); 24 | // reconstruct a bit - {src, dst, cost} 25 | for (auto f : flights) g.push_back({f[0], f[1], f[2]}); 26 | bellman_ford(g, cost, src, k); 27 | // if cost[dst] == 1e9, it means it is unreachable 28 | // else we can show cost[dst] 29 | return cost[dst] == 1e9 ? -1 : cost[dst]; 30 | } 31 | }; -------------------------------------------------------------------------------- /day27.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findAllConcatenatedWordsInADict(vector& words) { 4 | vector ans; 5 | unordered_set wordSet{begin(words), end(words)}; 6 | unordered_map memo; 7 | 8 | for (const string& word : words) 9 | if (isConcat(word, wordSet, memo)) 10 | ans.push_back(word); 11 | 12 | return ans; 13 | } 14 | 15 | private: 16 | bool isConcat(const string& s, const unordered_set& wordSet, 17 | unordered_map& memo) { 18 | if (memo.count(s)) 19 | return memo[s]; 20 | 21 | for (int i = 1; i < s.length(); ++i) { 22 | const string prefix = s.substr(0, i); 23 | const string suffix = s.substr(i); 24 | if (wordSet.count(prefix) && 25 | (wordSet.count(suffix) || isConcat(suffix, wordSet, memo))) 26 | return memo[s] = true; 27 | } 28 | 29 | return memo[s] = false; 30 | } 31 | }; -------------------------------------------------------------------------------- /day28.c++: -------------------------------------------------------------------------------- 1 | class SummaryRanges { 2 | public: 3 | set nums; 4 | SummaryRanges() { 5 | 6 | } 7 | 8 | void addNum(int value) { 9 | nums.insert(value); 10 | } 11 | 12 | vector> getIntervals() { 13 | vector> intervals; 14 | int start = *nums.begin(); 15 | int end = *nums.begin(); 16 | for (auto it = ++nums.begin(); it != nums.end(); it++) { 17 | int val = *it; 18 | if (val - end == 1) { 19 | end = val; 20 | } else { 21 | intervals.push_back({start, end}); 22 | start = end = val; 23 | } 24 | } 25 | intervals.push_back({start, end}); 26 | return intervals; 27 | 28 | } 29 | }; 30 | 31 | /** 32 | * Your SummaryRanges object will be instantiated and called as such: 33 | * SummaryRanges* obj = new SummaryRanges(); 34 | * obj->addNum(value); 35 | * vector> param_2 = obj->getIntervals(); 36 | */ -------------------------------------------------------------------------------- /day3.c++: -------------------------------------------------------------------------------- 1 | /*You are given an array of n strings strs, all of the same length. 2 | 3 | The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as: 4 | 5 | abc 6 | bce 7 | cae 8 | You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), 9 | columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted while column 1 10 | ('b', 'c', 'a') is not, so you would delete column 1. 11 | */ 12 | 13 | class Solution { 14 | public: 15 | int minDeletionSize(vector& A) { 16 | const int n = A[0].length(); 17 | int ans = 0; 18 | 19 | for (int j = 0; j < n; ++j) 20 | for (int i = 0; i + 1 < A.size(); ++i) 21 | if (A[i][j] > A[i + 1][j]) { 22 | ++ans; 23 | break; 24 | } 25 | 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /day30.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int tribonacci(int n) { 4 | if(n == 0) 5 | return 0; 6 | if(n == 1 || n == 2) 7 | return 1; 8 | vector Tribonacci(n+1); 9 | Tribonacci[0] = 0; 10 | Tribonacci[1] = 1; 11 | Tribonacci[2] = 1; 12 | for(int i = 3; i < n+1; i++){ 13 | Tribonacci[i] = Tribonacci[i-1] + Tribonacci[i-2] + Tribonacci[i-3]; 14 | } 15 | return Tribonacci[n]; 16 | } 17 | }; -------------------------------------------------------------------------------- /day31.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int bestTeamScore(vector& scores, vector& ages) { 4 | vector> items; 5 | for (int i = 0; i < size(scores); ++i) items.push_back({scores[i], ages[i]}); 6 | sort(begin(items), end(items)); 7 | 8 | map res; res[0] = 0; 9 | for(auto [sc, ag] : items) { 10 | auto it0 = res.upper_bound(ag); 11 | int sc2 = sc + (--it0)->second; 12 | auto it = res.insert(it0, {ag, sc2}); 13 | if (it->second < sc2) it->second = sc2; 14 | ++it; 15 | while (it != res.end() && it->second <= sc2) { 16 | auto it2 = it++; 17 | res.erase(it2); 18 | } 19 | } 20 | return res.rbegin()->second; 21 | } 22 | }; -------------------------------------------------------------------------------- /day33.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int orderMap[26]; 4 | bool isAlienSorted(vector& words, string order) { 5 | for (int i = 0; i < order.length(); i++){ 6 | orderMap[order[i] - 'a'] = i; 7 | } 8 | 9 | for(int i =1;i< words.size();i++){ 10 | if(!compare(words[i],words[i-1]))return false; 11 | } 12 | return true; 13 | } 14 | 15 | bool compare(string s1, string s2){ 16 | int j = 0; 17 | while(jorderMap[s2[j]-'a']) return true; 20 | else return false; 21 | } 22 | if(s1.length()v(numRows, ""); 9 | 10 | int j = 0, dir = -1; 11 | 12 | for(int i = 0; i < s.length(); i++) 13 | { 14 | 15 | if(j == numRows - 1 || j == 0) dir *= (-1); 16 | 17 | v[j] += s[i]; 18 | 19 | if(dir == 1) j++; 20 | 21 | else j--; 22 | } 23 | 24 | string res; 25 | 26 | for(auto &it : v) res += it; 27 | 28 | return res; 29 | 30 | } 31 | }; -------------------------------------------------------------------------------- /day35.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | bool areVectorsEqual(vector a, vector b){ 3 | for(int i=0; i<26; i++){ 4 | if(a[i]!=b[i]) return false; 5 | } 6 | return true; 7 | } 8 | public: 9 | bool checkInclusion(string s1, string s2) { 10 | if(s2.size() freqS1(26, 0); 12 | for(char c: s1) freqS1[c-'a']++; 13 | 14 | vector freqS2(26, 0); 15 | int i=0, j=0; 16 | 17 | while(j findAnagrams(string s, string p) { 4 | vector ans; 5 | vector hash(26, 0); 6 | vector phash(26, 0); 7 | int window = p.size(); 8 | int len = s.size(); 9 | if(len < window) 10 | { 11 | return ans; 12 | } 13 | int left = 0,right = 0; 14 | while(right < window) 15 | { 16 | phash[p[right] - 'a'] += 1; 17 | hash[s[right] - 'a'] += 1; 18 | right++; 19 | } 20 | right -=1; 21 | while(right < len) 22 | { 23 | if(phash == hash) 24 | { 25 | ans.push_back(left); 26 | } 27 | right+=1; 28 | if(right != len) 29 | { 30 | hash[s[right] - 'a'] += 1; 31 | } 32 | hash[s[left] - 'a'] -=1 ; 33 | left += 1; 34 | } 35 | return ans; 36 | } 37 | }; -------------------------------------------------------------------------------- /day37.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector shuffle(vector& nums, int n) { 4 | int first = 0, second = n, max = 1001; 5 | for(int i=0;i<2*n;i++) 6 | { 7 | if(i%2==0) 8 | nums[i]=(nums[first++]%max)*max + nums[i]; 9 | else 10 | nums[i]=(nums[second++]%max)*max + nums[i]; 11 | } 12 | for(int i=0;i<2*n;i++) 13 | nums[i]/=max; 14 | return nums; 15 | } 16 | }; -------------------------------------------------------------------------------- /day38.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int totalFruit(vector& fruits) { 5 | 6 | unordered_map mpp; 7 | 8 | int i = 0, j = 0, res = 0; 9 | 10 | while(j < fruits.size()) 11 | { 12 | 13 | mpp[fruits[j]]++; 14 | 15 | if(mpp.size() <= 2) 16 | { 17 | 18 | int temp = 0; 19 | 20 | for(auto &it : mpp) temp += it.second; 21 | 22 | res = max(res, temp); 23 | } 24 | 25 | else 26 | { 27 | mpp[fruits[i]]--; 28 | if(mpp[fruits[i]] == 0) mpp.erase(fruits[i]); 29 | i++; 30 | } 31 | 32 | j++; 33 | } 34 | 35 | return res; 36 | } 37 | }; -------------------------------------------------------------------------------- /day39.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int jump(vector& nums) { 5 | 6 | for(int i = 1; i < nums.size(); i++) 7 | { 8 | nums[i] = max(nums[i] + i, nums[i-1]); 9 | } 10 | 11 | int ind = 0; 12 | int ans = 0; 13 | 14 | while(ind < nums.size() - 1) 15 | { 16 | ans++; 17 | ind = nums[ind]; 18 | } 19 | 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /day4.c++: -------------------------------------------------------------------------------- 1 | /*You are given a 0-indexed integer array tasks, where tasks[i] represents the 2 | difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level. 3 | 4 | Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.*/ 5 | 6 | 7 | class Solution 8 | { 9 | public: 10 | int dp[100001]; 11 | bool flag = false; 12 | int minimumRounds(vector& tasks) 13 | { 14 | mapmp; 15 | for(auto & e:tasks) 16 | mp[e]++; 17 | if(!flag) 18 | { 19 | dp[0] = INT_MAX/2;dp[1] = INT_MAX/2; 20 | dp[2] = 1;dp[3] = 1; 21 | for(int i = 4;i<=100000;i++) 22 | dp[i] = min(dp[i-2],dp[i-3]) + 1; 23 | flag = true; 24 | } 25 | int ans = 0; 26 | for(auto it = mp.begin();it!=mp.end();it++) 27 | { 28 | if(it->second == 1) 29 | return -1; 30 | ans += dp[it->second]; 31 | } 32 | return ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /day40.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long distinctNames(vector& ideas) { 4 | long long disName = 0; 5 | vector> arr(26); 6 | for (string s : ideas) 7 | arr[s[0] - 'a'].insert(s.substr(1)); 8 | 9 | for (int i = 0; i < 25; i++) { 10 | for (int j = i + 1; j < 26; j++) { 11 | unordered_set set; 12 | set.insert(arr[i].begin(), arr[i].end()); 13 | set.insert(arr[j].begin(), arr[j].end()); 14 | disName += (arr[i].size() - set.size()) * (arr[j].size() - set.size()); 15 | } 16 | } 17 | return disName * 2; 18 | } 19 | }; -------------------------------------------------------------------------------- /day41.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int maxDistance(vector>& grid){ 5 | 6 | int n=grid.size(),m=grid[0].size(); 7 | 8 | queue>q; 9 | 10 | for(int i = 0; i < n; i++) 11 | { 12 | for(int j=0; j < m; j++) 13 | { 14 | if(grid[i][j] == 1) q.push({i,j}); 15 | } 16 | } 17 | 18 | int res = 0; 19 | 20 | while(!q.empty()) 21 | { 22 | 23 | int temp_i = q.front().first; 24 | int temp_j = q.front().second; 25 | q.pop(); 26 | 27 | vector>dir = {{0,1},{0,-1},{1,0},{-1,0}}; 28 | 29 | for(auto &it : dir) 30 | { 31 | 32 | int new_i= it.first + temp_i; 33 | int new_j= it.second + temp_j; 34 | 35 | if(new_i>=0 && new_i=0 && new_j[][] graph = new HashSet[2][n]; 5 | for (int i = 0; i < n; i++) { 6 | graph[0][i] = new HashSet<>(); 7 | graph[1][i] = new HashSet<>(); 8 | } 9 | // red edges in 0 - col 10 | for (int[] re : red_edges) { 11 | graph[0][ re[0] ].add(re[1]); 12 | } 13 | // blu edges in 1 - col 14 | for (int[] blu : blue_edges) { 15 | graph[1][ blu[0] ].add(blu[1]); 16 | } 17 | int[][] res = new int[2][n]; 18 | // Zero edge is always accessible to itself - leave it as 0 19 | for (int i = 1; i < n; i++) { 20 | res[0][i] = 2 * n; 21 | res[1][i] = 2 * n; 22 | } 23 | // Q entries are vert with a color (up to that point) 24 | Queue q = new LinkedList<>(); 25 | q.offer(new int[] {0, 0}); // either with red 26 | q.offer(new int[] {0, 1}); // or with blue 27 | while (!q.isEmpty()) { 28 | int[] cur = q.poll(); 29 | int vert = cur[0]; 30 | int colr = cur[1]; 31 | // No need to keep track of level up to now 32 | // only need to keep what color - and the length 33 | // is automatically derived from previous node 34 | for (int nxt : graph[1 - colr][vert]) { 35 | if (res[1 - colr][nxt] == 2 * n) { 36 | res[1 - colr][nxt] = 1 + res[colr][vert]; 37 | q.offer(new int[] {nxt, 1 - colr}); 38 | } 39 | } 40 | } 41 | int[] ans = new int[n]; 42 | for (int i = 0; i < n; i++) { 43 | int t = Math.min(res[0][i], res[1][i]); 44 | ans[i] = (t == 2 * n) ? -1 : t; 45 | } 46 | return ans; 47 | } 48 | } -------------------------------------------------------------------------------- /day43.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long minimumFuelCost(vector>& roads, int seats) { 4 | long long ans = 0; 5 | vector> graph(roads.size() + 1); 6 | 7 | for (const vector& road : roads) { 8 | const int u = road[0]; 9 | const int v = road[1]; 10 | graph[u].push_back(v); 11 | graph[v].push_back(u); 12 | } 13 | 14 | dfs(graph, 0, -1, seats, ans); 15 | return ans; 16 | } 17 | 18 | private: 19 | int dfs(const vector>& graph, int u, int prev, int seats, 20 | long long& ans) { 21 | int people = 1; 22 | for (const int v : graph[u]) { 23 | if (v == prev) 24 | continue; 25 | people += dfs(graph, v, u, seats, ans); 26 | } 27 | if (u > 0) 28 | // # of cars needed = ceil(people / seats) 29 | ans += (people + seats - 1) / seats; 30 | return people; 31 | } 32 | }; -------------------------------------------------------------------------------- /day44.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countOdds(int l, int h) { 4 | return ((h + 1) / 2) - (l / 2); 5 | } 6 | }; -------------------------------------------------------------------------------- /day45.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Function to add two binary numbers represented as strings 4 | string addBinary(string a, string b) { 5 | // Initialize two pointers to traverse the binary strings from right to left 6 | int i = a.length()-1; 7 | int j = b.length()-1; 8 | string ans; 9 | int carry = 0; 10 | 11 | // Loop until both pointers have reached the beginning of their respective strings and there is no carry-over value left 12 | while(i >= 0 || j >= 0 || carry) { 13 | // Add the current binary digit in string a, if the pointer is still within bounds 14 | if(i >= 0) { 15 | carry += a[i] - '0'; 16 | i--; 17 | } 18 | 19 | // Add the current binary digit in string b, if the pointer is still within bounds 20 | if(j >= 0) { 21 | carry += b[j] - '0'; 22 | j--; 23 | } 24 | 25 | // Calculate the next binary digit in the result by taking the remainder of the sum divided by 2 26 | ans += (carry % 2 + '0'); 27 | 28 | // Calculate the next carry-over value by dividing the sum by 2 29 | carry = carry / 2; 30 | } 31 | 32 | // Reverse the result and return it as a string 33 | reverse(ans.begin(), ans.end()); 34 | return ans; 35 | } 36 | }; -------------------------------------------------------------------------------- /day46.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector addToArrayForm(vector& num, int k) { 4 | vector ans; 5 | int n = num.size(); 6 | int carry = 0, i = n-1; 7 | while (k > 0 || i >= 0 || carry > 0) { 8 | int sum = carry; 9 | if (k > 0) { 10 | int remainder = k % 10; 11 | sum += remainder; 12 | k = k / 10; 13 | } 14 | if (i >= 0) { 15 | sum += num[i]; 16 | i--; 17 | } 18 | carry = sum / 10; 19 | ans.push_back(sum % 10); 20 | } 21 | reverse(ans.begin(), ans.end()); 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /day47.c++: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int maxDepth(TreeNode* root) { 15 | if(!root) return 0; 16 | int maxLeft = maxDepth(root->left); 17 | int maxRight = maxDepth(root->right); 18 | return max(maxLeft, maxRight)+1; 19 | } 20 | }; -------------------------------------------------------------------------------- /day48.c++: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void helper(TreeNode* root, vector& storeNodeVal) { 15 | if(root == nullptr) 16 | return; 17 | helper(root -> left, storeNodeVal); 18 | storeNodeVal.push_back(root -> val); 19 | helper(root -> right, storeNodeVal); 20 | } 21 | int minDiffInBST(TreeNode* root) { 22 | vector storeNodeVal; 23 | helper(root, storeNodeVal); 24 | int minDiff = INT_MAX; 25 | for (int i = 0; i < storeNodeVal.size()-1; i++) { 26 | minDiff = min(minDiff, storeNodeVal[i+1] - storeNodeVal[i]); 27 | } 28 | return minDiff; 29 | } 30 | }; -------------------------------------------------------------------------------- /day49.c++: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* invertTree(TreeNode* root) { 15 | 16 | if(root == NULL) return root; 17 | swap(root->left, root->right); 18 | invertTree(root->left); 19 | invertTree(root->right); 20 | 21 | return root; 22 | } 23 | }; -------------------------------------------------------------------------------- /day5.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMinArrowShots(vector>& points) { 4 | sort(begin(points), end(points), 5 | [](const auto& a, const auto& b) { return a[1] < b[1]; }); 6 | 7 | int ans = 1; 8 | int arrowX = points[0][1]; 9 | 10 | for (int i = 1; i < points.size(); ++i) 11 | if (points[i][0] > arrowX) { 12 | arrowX = points[i][1]; 13 | ++ans; 14 | } 15 | 16 | return ans; 17 | } 18 | }; -------------------------------------------------------------------------------- /day50.c++: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector> zigzagLevelOrder(TreeNode* root) { 15 | vector>ans; 16 | if(!root)return ans; 17 | queueq; 18 | q.push(root); 19 | int i=0; 20 | while(!q.empty()){ 21 | int sz=q.size(); 22 | vectorv; 23 | while(sz--){ 24 | TreeNode * f=q.front(); 25 | v.push_back(q.front()->val); 26 | q.pop(); 27 | if(f->left)q.push(f->left); 28 | if(f->right)q.push(f->right); 29 | 30 | } 31 | if(i++%2) 32 | reverse(v.begin(),v.end()); 33 | ans.push_back(v); 34 | 35 | } 36 | return ans; 37 | 38 | } 39 | }; -------------------------------------------------------------------------------- /day51.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | int low=0; 5 | int high=nums.size(); 6 | int mid; 7 | if(target>nums[high-1]){ 8 | return high; 9 | } 10 | while(low<=high){ 11 | mid=(low+high)/2; 12 | if(nums[mid]==target){ //if found return its position 13 | return mid; 14 | } 15 | 16 | if(target& nums) { 4 | if(nums.size() == 1) return nums[0]; 5 | int low = 0; 6 | int high = nums.size() - 1; 7 | 8 | if (nums[0] != nums[1]) return nums[0]; 9 | 10 | if (nums[high] != nums[high - 1]) return nums[high]; 11 | 12 | while (low <= high) { 13 | int mid = low + (high - low) / 2; 14 | if (nums[mid] != nums[mid - 1] && nums[mid] != nums[mid + 1]) { 15 | return nums[mid]; 16 | } 17 | else if ((nums[mid] == nums[mid + 1] && mid % 2 == 0) || (nums[mid] == nums[mid - 1] && mid % 2 != 0)) { 18 | low = mid + 1; 19 | } 20 | else { 21 | high = mid - 1; 22 | } 23 | } 24 | return nums[low]; 25 | } 26 | }; -------------------------------------------------------------------------------- /day53.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int shipWithinDays(vector& weights, int days) { 4 | int maxWeight = -1, totalWeight = 0; 5 | for (int weight : weights) { 6 | maxWeight = max(maxWeight, weight); 7 | totalWeight = totalWeight + weight; 8 | } 9 | //here weight and total weight work as left and right pointer of bunary search 10 | while (maxWeight < totalWeight) { 11 | int midWeight = maxWeight + (totalWeight - maxWeight) / 2; 12 | int daysNeeded = 1, currWeight = 0; 13 | for (int weight : weights) { 14 | if (currWeight + weight > midWeight) { 15 | daysNeeded++; 16 | currWeight = 0; 17 | } 18 | currWeight = currWeight + weight; 19 | } 20 | if (daysNeeded > days) { 21 | maxWeight = midWeight + 1; 22 | } else { 23 | totalWeight = midWeight; 24 | } 25 | } 26 | return maxWeight; 27 | } 28 | }; -------------------------------------------------------------------------------- /day54.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaximizedCapital(int k, int w, vector& profits, vector& capital) { 4 | int n = profits.size(); 5 | vector> projects(n); 6 | for (int i = 0; i < n; i++) { 7 | projects[i] = {capital[i], profits[i]}; 8 | } 9 | sort(projects.begin(), projects.end()); 10 | int i = 0; 11 | priority_queue maximizeCapital; 12 | while (k--) { 13 | 14 | while (i < n && projects[i].first <= w) { 15 | maximizeCapital.push(projects[i].second); 16 | i++; 17 | } 18 | if (maximizeCapital.empty()) 19 | break; 20 | w += maximizeCapital.top(); 21 | maximizeCapital.pop(); 22 | } 23 | return w; 24 | } 25 | }; -------------------------------------------------------------------------------- /day56.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int n = prices.size(); 5 | int maximumProfit = 0, minStockVal = INT_MAX; 6 | int i = 0; 7 | while (i < n) { 8 | minStockVal = min(minStockVal, prices[i]); 9 | // whenever the price of current stock is greater then then the stock value which we bought then only we will sell the stock 10 | if (prices[i] >= minStockVal) 11 | maximumProfit = max(maximumProfit, prices[i] - minStockVal); 12 | i++; 13 | } 14 | return maximumProfit; 15 | } 16 | }; -------------------------------------------------------------------------------- /day57.c++: -------------------------------------------------------------------------------- 1 | /* 2 | // Definition for a QuadTree node. 3 | class Node { 4 | public: 5 | bool val; 6 | bool isLeaf; 7 | Node* topLeft; 8 | Node* topRight; 9 | Node* bottomLeft; 10 | Node* bottomRight; 11 | 12 | Node() { 13 | val = false; 14 | isLeaf = false; 15 | topLeft = NULL; 16 | topRight = NULL; 17 | bottomLeft = NULL; 18 | bottomRight = NULL; 19 | } 20 | 21 | Node(bool _val, bool _isLeaf) { 22 | val = _val; 23 | isLeaf = _isLeaf; 24 | topLeft = NULL; 25 | topRight = NULL; 26 | bottomLeft = NULL; 27 | bottomRight = NULL; 28 | } 29 | 30 | Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) { 31 | val = _val; 32 | isLeaf = _isLeaf; 33 | topLeft = _topLeft; 34 | topRight = _topRight; 35 | bottomLeft = _bottomLeft; 36 | bottomRight = _bottomRight; 37 | } 38 | }; 39 | */ 40 | 41 | class Solution { 42 | public: 43 | Node* constructQuadTree(vector>& grid, int rowStart, int rowEnd, int colStart, int colEnd) { 44 | if (rowStart > rowEnd || colStart > colEnd) { 45 | return nullptr; 46 | } 47 | 48 | // Check if all elements in the quadrant are the same 49 | bool isLeaf = true; 50 | int val = grid[rowStart][colStart]; 51 | for (int i = rowStart; i <= rowEnd; i++) { 52 | for (int j = colStart; j <= colEnd; j++) { 53 | if (grid[i][j] != val) { 54 | isLeaf = false; 55 | break; 56 | } 57 | } 58 | if (!isLeaf) { 59 | break; 60 | } 61 | } 62 | 63 | // If all elements in the quadrant are the same, create a new leaf node 64 | if (isLeaf) { 65 | return new Node(val, true); 66 | } 67 | 68 | // Otherwise, divide the quadrant into four sub-quadrants and recursively construct the quad-tree for each sub-quadrant 69 | int rowMid = (rowStart + rowEnd) / 2; 70 | int colMid = (colStart + colEnd) / 2; 71 | Node* topLeft = constructQuadTree(grid, rowStart, rowMid, colStart, colMid); 72 | Node* topRight = constructQuadTree(grid, rowStart, rowMid, colMid+1, colEnd); 73 | Node* bottomLeft = constructQuadTree(grid, rowMid+1, rowEnd, colStart, colMid); 74 | Node* bottomRight = constructQuadTree(grid, rowMid+1, rowEnd, colMid+1, colEnd); 75 | return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight); 76 | } 77 | Node* construct(vector>& grid) { 78 | int n = grid.size(); 79 | return constructQuadTree(grid, 0, n-1, 0, n-1); 80 | } 81 | }; -------------------------------------------------------------------------------- /day58.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // Serialize subtrees and check for duplicates using a post-order traversal 4 | string serializeSubtrees(TreeNode* node, unordered_map& subtrees, vector& duplicates) { 5 | if (!node) return "#"; // Null nodes are represented by '#' 6 | 7 | string left = serializeSubtrees(node->left, subtrees, duplicates); 8 | string right = serializeSubtrees(node->right, subtrees, duplicates); 9 | 10 | string s = left + "," + right + "," + to_string(node->val); // Serialize the current subtree 11 | 12 | if (subtrees[s] == 1) duplicates.push_back(node); // If a duplicate subtree is found, add to the vector 13 | 14 | subtrees[s]++; 15 | return s; 16 | } 17 | vector findDuplicateSubtrees(TreeNode* root) { 18 | unordered_map subtrees; // Store serialized subtree and its frequency 19 | vector duplicates; // Store duplicate subtrees 20 | 21 | serializeSubtrees(root, subtrees, duplicates); // Traverse the tree and serialize subtrees 22 | 23 | return duplicates; 24 | } 25 | 26 | }; -------------------------------------------------------------------------------- /day6.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxIceCream(vector& costs, int coins) { 4 | sort(begin(costs), end(costs)); 5 | 6 | for (int i = 0; i < costs.size(); ++i) 7 | if (coins >= costs[i]) 8 | coins -= costs[i]; 9 | else 10 | return i; 11 | 12 | return costs.size(); 13 | } 14 | }; -------------------------------------------------------------------------------- /day60.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector mergesorted(vector&arr) 4 | { 5 | if(arr.size()==1) 6 | { 7 | return arr; 8 | } 9 | int dividesize=arr.size()/2; 10 | vectormerge1,merge2; 11 | for(int i=0;i sortArray(vector&nums) 54 | { 55 | return mergesorted(nums); 56 | } 57 | }; -------------------------------------------------------------------------------- /day61.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int compress(vector& chars) { 4 | if (chars.empty()) return 0; 5 | char curr = chars[0]; 6 | int count = 1; 7 | string s; 8 | for (int i = 1; i <= chars.size(); i++) { 9 | if (i < chars.size() && chars[i] == curr) { 10 | count++; 11 | } else { 12 | s.push_back(curr); 13 | if (count > 1) { 14 | string str = to_string(count); 15 | for (char c : str) { 16 | s.push_back(c); 17 | } 18 | } 19 | curr = i < chars.size() ? chars[i] : 0; 20 | count = 1; 21 | } 22 | } 23 | for (int i = 0; i < s.size(); i++) { 24 | chars[i] = s[i]; 25 | } 26 | return s.size(); 27 | } 28 | }; -------------------------------------------------------------------------------- /day63.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long countSubarrays(vector& A, int minK, int maxK) { 4 | long res = 0, jbad = -1, jmin = -1, jmax = -1, n = A.size(); 5 | for (int i = 0; i < n; ++i) { 6 | if (A[i] < minK || A[i] > maxK) jbad = i; 7 | if (A[i] == minK) jmin = i; 8 | if (A[i] == maxK) jmax = i; 9 | res += max(0L, min(jmin, jmax) - jbad); 10 | } 11 | return res; 12 | } 13 | }; -------------------------------------------------------------------------------- /day65.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findKthPositive(vector& arr, int k) { 4 | int lo = 0, hi = arr.size(); 5 | while (lo < hi) { 6 | int mid = lo + (hi - lo) / 2; 7 | if (arr[mid] - mid > k) hi = mid; 8 | else lo = mid + 1; 9 | } 10 | return lo + k; 11 | } 12 | }; -------------------------------------------------------------------------------- /day66.c++: -------------------------------------------------------------------------------- 1 | #define ll long long 2 | class Solution { 3 | public: 4 | long long minimumTime(vector& time, int totalTrips) { 5 | ll start = 1; 6 | ll end = 1e14; 7 | while(start <= end){ 8 | ll trip = 0; 9 | ll mid = start + (end - start)/2; 10 | for(int i=0;inext!=NULL && fast->next->next!=NULL){ 16 | slow=slow->next; 17 | fast=fast->next->next; 18 | if(slow==fast){ //meet point 19 | while(curr!=fast){ 20 | fast=fast->next; 21 | curr=curr->next; 22 | } 23 | return fast; 24 | 25 | } 26 | } 27 | return NULL; 28 | 29 | } 30 | }; -------------------------------------------------------------------------------- /day69.c++: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | 14 | vector nodes; 15 | 16 | Solution(ListNode* head) { 17 | while(head!=NULL) 18 | { 19 | nodes.push_back(head); 20 | head=head->next; 21 | } 22 | } 23 | 24 | int getRandom() { 25 | 26 | int n=nodes.size(); 27 | int radn=rand()%n; 28 | return nodes[radn]->val; 29 | 30 | } 31 | }; 32 | 33 | /** 34 | * Your Solution object will be instantiated and called as such: 35 | * Solution* obj = new Solution(head); 36 | * int param_1 = obj->getRandom(); 37 | */ -------------------------------------------------------------------------------- /day7.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int canCompleteCircuit(vector& gas, vector& cost) { 4 | int n=gas.size(); 5 | int total_gas=0,total_cost=0; 6 | int curr_gas=0, starting_point=0; 7 | for(int i=0;inext == NULL) return new TreeNode(head->val); 27 | ListNode* middle = getMiddle(head); 28 | TreeNode* root = new TreeNode(middle->val); 29 | root->right = sortedListToBST(middle->next); 30 | middle->next = NULL; 31 | root->left = sortedListToBST(head); 32 | return root; 33 | } 34 | 35 | ListNode* getMiddle(ListNode* head){ 36 | //if(head == NULL || head->next==NULL) return NULL; 37 | ListNode* fast = head; 38 | ListNode* slow = head; 39 | ListNode* prev = NULL; 40 | while(fast!=NULL && fast->next!=NULL){ 41 | fast = fast->next->next; 42 | prev = slow; 43 | slow = slow->next; 44 | } 45 | if(prev!=NULL) prev->next = NULL; 46 | return slow; 47 | } 48 | }; -------------------------------------------------------------------------------- /day71.c++: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | // } Driver Code Ends 10 | //User function Template for C++ 11 | 12 | class Solution { 13 | public: 14 | vector findMaxRow(vector> mat, int N) { 15 | //code here 16 | int mxcount = 0; 17 | int row_num = 0; 18 | for(int i = 0; i::iterator upper; 20 | upper = upper_bound(mat[i].begin(), mat[i].end(), 0) ; 21 | int temp = N - (upper - mat[i].begin()); 22 | if(temp > mxcount){ 23 | mxcount = temp; 24 | row_num = i; 25 | } 26 | } 27 | return {row_num , mxcount}; 28 | } 29 | }; 30 | 31 | //{ Driver Code Starts. 32 | 33 | int main() { 34 | int t; 35 | cin>>t; 36 | while(t--) { 37 | int n; 38 | cin>>n; 39 | vector> arr(n, vector (n)); 40 | for(int i = 0; i < n; i++) 41 | for(int j = 0; j < n; j++) 42 | cin >> arr[i][j]; 43 | Solution obj; 44 | vector ans = obj.findMaxRow(arr, n); 45 | for(int val : ans) { 46 | cout << val << " "; 47 | } 48 | cout << endl; 49 | } 50 | } 51 | // } Driver Code Ends -------------------------------------------------------------------------------- /day72.c++: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isSymmetric(TreeNode* root) { 15 | return isMirror(root, root); 16 | } 17 | 18 | bool isMirror(TreeNode* t1, TreeNode* t2) { 19 | if (t1 == nullptr && t2 == nullptr) { 20 | return true; 21 | } 22 | if (t1 == nullptr || t2 == nullptr) { 23 | return false; 24 | } 25 | return t1->val == t2->val && isMirror(t1->right, t2->left) && isMirror(t1->left, t2->right); 26 | } 27 | }; -------------------------------------------------------------------------------- /day73.c++: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int sumNumbers(TreeNode* root) { 15 | int result = 0; 16 | dfs(root, 0, result); 17 | return result; 18 | } 19 | 20 | private: 21 | void dfs(TreeNode* node, int currSum, int& result) { 22 | if (!node) return; 23 | 24 | currSum = currSum * 10 + node->val; 25 | if (!node->left && !node->right) { 26 | result += currSum; 27 | return; 28 | } 29 | 30 | dfs(node->left, currSum, result); 31 | dfs(node->right, currSum, result); 32 | } 33 | }; -------------------------------------------------------------------------------- /day74.c++: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isCompleteTree(TreeNode* root) { 15 | queue q; 16 | q.push(root); 17 | while (q.front() != NULL) { 18 | TreeNode* node = q.front(); 19 | q.pop(); 20 | q.push(node->left); 21 | q.push(node->right); 22 | } 23 | while (!q.empty() && q.front() == NULL) { 24 | q.pop(); 25 | } 26 | return q.empty(); 27 | } 28 | }; -------------------------------------------------------------------------------- /day76.c++: -------------------------------------------------------------------------------- 1 | class TrieNode { 2 | public: 3 | bool isWord; 4 | TrieNode* children[26]; 5 | 6 | TrieNode() { 7 | isWord = false; 8 | memset(children, 0, sizeof(children)); // Initialize all children to null 9 | } 10 | }; 11 | 12 | class Trie { 13 | private: 14 | TrieNode* root; 15 | 16 | public: 17 | Trie() { 18 | root = new TrieNode(); 19 | } 20 | 21 | void insert(string word) { 22 | TrieNode* node = root; 23 | for (char c : word) { 24 | int index = c - 'a'; 25 | if (!node->children[index]) { 26 | node->children[index] = new TrieNode(); 27 | } 28 | node = node->children[index]; 29 | } 30 | node->isWord = true; 31 | } 32 | 33 | bool search(string word) { 34 | TrieNode* node = root; 35 | for (char c : word) { 36 | int index = c - 'a'; 37 | if (!node->children[index]) { 38 | return false; 39 | } 40 | node = node->children[index]; 41 | } 42 | return node->isWord; 43 | } 44 | 45 | bool startsWith(string prefix) { 46 | TrieNode* node = root; 47 | for (char c : prefix) { 48 | int index = c - 'a'; 49 | if (!node->children[index]) { 50 | return false; 51 | } 52 | node = node->children[index]; 53 | } 54 | return true; 55 | } 56 | }; 57 | /** 58 | * Your Trie object will be instantiated and called as such: 59 | * Trie* obj = new Trie(); 60 | * obj->insert(word); 61 | * bool param_2 = obj->search(word); 62 | * bool param_3 = obj->startsWith(prefix); 63 | */ -------------------------------------------------------------------------------- /day79.c++: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canPlaceFlowers(vector& fd, int n) { 4 | int pre =1; 5 | for(int i =0; i>& points) { 10 | int n = points.size(); 11 | if (n == 0) 12 | return 0; 13 | int res = 0; 14 | for (int i = 0; i < n; ++i) 15 | { 16 | int x1 = points[i][0]; 17 | int y1 = points[i][1]; 18 | int dup = 1; 19 | int subRes = 0; 20 | unordered_map> umap; 21 | for (int j = i + 1; j < n; ++j) 22 | { 23 | int x2 = points[j][0]; 24 | int y2 = points[j][1]; 25 | if (x1 == x2 && y1 == y2) 26 | { 27 | dup++; 28 | } 29 | else 30 | { 31 | int diffX = x2 - x1; 32 | int diffY = y2 - y1; 33 | int diffGCD = getGCD(diffX, diffY); 34 | diffX /= diffGCD; 35 | diffY /= diffGCD; 36 | umap[diffX][diffY]++; 37 | subRes = std::max(subRes, umap[diffX][diffY]); 38 | } 39 | } 40 | res = std::max(res, subRes + dup); 41 | } 42 | return res; 43 | } 44 | }; -------------------------------------------------------------------------------- /day9.c++: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector ans; 15 | 16 | void preorder(TreeNode* node){ 17 | if(!node) return; 18 | ans.push_back(node->val); 19 | preorder(node->left); 20 | preorder(node->right); 21 | } 22 | 23 | vector preorderTraversal(TreeNode* root) { 24 | preorder(root); 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /may 2023/1may.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static double average(int[] salary) { 3 | double min = Double.MAX_VALUE, max = Double.MIN_VALUE, avg = 0.0, sum = 0.0; 4 | for (int i = 0; i < salary.length; i++) { 5 | min = Math.min(salary[i], min); 6 | max = Math.max(salary[i], max); 7 | sum += salary[i]; 8 | } 9 | 10 | avg = sum - min - max; 11 | return avg / (salary.length - 2); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /may 2023/2may.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int arraySign(int[] nums) { 3 | int sign = 1; 4 | 5 | for (final int num : nums) { 6 | if (num == 0) 7 | return 0; 8 | if (num < 0) 9 | sign = -sign; 10 | } 11 | 12 | return sign; 13 | } 14 | } 15 | --------------------------------------------------------------------------------