├── .DS_Store
├── .idea
├── misc.xml
├── vcs.xml
└── workspace.xml
├── Interview-Preparation-Java.iml
├── README.md
├── out
└── production
│ └── Interview-Preparation-Java
│ └── slidingwindow
│ ├── AverageSubarrayOfSizeK.class
│ └── MaxSubarraySum.class
└── src
├── .DS_Store
├── backtracking
├── StringPermutations.class
├── StringPermutations.java
├── Subset.class
└── Subset.java
├── dynamicprogramming
├── memoization
│ ├── ClimbingStairs.class
│ ├── ClimbingStairs.java
│ ├── Knapsack.class
│ ├── Knapsack.java
│ ├── LongestCommonSubsequence.class
│ ├── LongestCommonSubsequence.java
│ ├── UnboundedKnapsack.class
│ └── UnboundedKnapsack.java
└── tabulation
│ ├── Base.class
│ ├── ClimbingStairs.class
│ ├── ClimbingStairs.java
│ ├── Derived.class
│ ├── Knapsack.class
│ ├── Knapsack.java
│ ├── LongestCommonSubsequence.class
│ ├── LongestCommonSubsequence.java
│ ├── UnboundedKnapsack.class
│ └── UnboundedKnapsack.java
├── graph
├── AdjacencyList.java
├── AdjacencyMatrix.java
├── AlienDictionary.class
├── AlienDictionary.java
├── CountNodesInDisconnectedComponents.java
├── CourseSchedule.class
├── CourseSchedule.java
├── CriticalEdgesPseudoCriticalEdges.java
├── DSU.class
├── DSU.java
├── DepthFirstSearch.java
├── DijkstraAlgorithm.class
├── DijkstraAlgorithm.java
├── DisconnectedComponents.java
├── KruskalsAlgo.class
├── KruskalsAlgo.java
├── MinCostToConnectAllPoints.java
├── Pair.class
├── PrimsAlgorithm.class
├── PrimsAlgorithm.java
├── RoadsAndLibraries.java
├── RottenOranges.java
├── TopologicalOrdering.java
├── WaterOptimization.class
└── WaterOptimization.java
├── linkedlist
├── DesignLinkedList.class
├── DesignLinkedList.java
├── LFUCache.java
└── Node.class
├── maths
├── SplitArrayGCD.class
└── SplitArrayGCD.java
├── priorityqueue
├── FrequencySort.java
├── KClosestPointsToOrigin.java
├── LargestKElements.class
├── LargestKElements.java
├── MeetingRoomsII.class
├── MeetingRoomsII.java
├── ReorganizeString.java
├── ReorganizeStringKDistanceApart.class
├── ReorganizeStringKDistanceApart.java
└── SmallestKElements.java
├── recursion
├── ClimbingStairs.java
├── DishDistribution.class
├── DishDistribution.java
├── MaximumPriceProblem.class
├── MaximumPriceProblem.java
├── MinCostClimbingStairs.java
├── StoneGame.java
├── StoneGame3.java
└── StoneGameRaw.java
├── slidingwindow
├── .DS_Store
├── AllAnagrams.java
├── AverageSubarrayOfSizeK.java
├── KDistinctCharacters.class
├── KDistinctCharacters.java
├── LongestSubstringAfterReplacement.class
├── LongestSubstringAfterReplacement.java
├── MaxSubarraySum.java
├── NoRepeatSubstring.java
├── PermutationInString.class
├── PermutationInString.java
└── SubarrayWithKDistinctCharacters.java
├── stack
├── InfixToPostfix.class
├── InfixToPostfix.java
├── MaximumAreaHistogram.class
├── MaximumAreaHistogram.java
├── NGER.class
├── NGER.java
├── NSER.class
├── NSER.java
├── PostfixEvaluation.class
├── PostfixEvaluation.java
├── StockSpan.class
└── StockSpan.java
└── trie
└── DesignTrie.java
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/.DS_Store
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/workspace.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | {
32 | "keyToString": {
33 | "RunOnceActivity.OpenProjectViewOnStart": "true",
34 | "RunOnceActivity.ShowReadmeOnStart": "true",
35 | "project.structure.last.edited": "Project",
36 | "project.structure.proportion": "0.15",
37 | "project.structure.side.proportion": "0.2",
38 | "settings.editor.selected.configurable": "project.propDebugger"
39 | }
40 | }
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 | 1669010862127
153 |
154 |
155 | 1669010862127
156 |
157 |
158 |
159 |
160 |
161 |
168 |
169 |
170 |
--------------------------------------------------------------------------------
/Interview-Preparation-Java.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Interview-Preparation-Java
2 |
3 |
4 |
5 | This repository has all the problems asked in product-based companies interviews and online assessments.
6 |
--------------------------------------------------------------------------------
/out/production/Interview-Preparation-Java/slidingwindow/AverageSubarrayOfSizeK.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/out/production/Interview-Preparation-Java/slidingwindow/AverageSubarrayOfSizeK.class
--------------------------------------------------------------------------------
/out/production/Interview-Preparation-Java/slidingwindow/MaxSubarraySum.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/out/production/Interview-Preparation-Java/slidingwindow/MaxSubarraySum.class
--------------------------------------------------------------------------------
/src/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/.DS_Store
--------------------------------------------------------------------------------
/src/backtracking/StringPermutations.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/backtracking/StringPermutations.class
--------------------------------------------------------------------------------
/src/backtracking/StringPermutations.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class StringPermutations {
4 |
5 | public static void swap(StringBuilder str, int i, int j) {
6 | char ch = str.charAt(i);
7 | str.setCharAt(i, str.charAt(j));
8 | str.setCharAt(j, ch);
9 | }
10 |
11 | public static void solve(StringBuilder str, int start, List result) {
12 | if(start >= str.length() - 1) {
13 | result.add(str.toString());
14 | return;
15 | }
16 | for(int i = start; i < str.length(); i++) {
17 | StringPermutations.swap(str, i, start);
18 | StringPermutations.solve(str, start + 1, result);
19 | StringPermutations.swap(str, i, start);
20 | }
21 | }
22 |
23 | public static List permute(String string) {
24 | List result = new ArrayList();
25 | StringPermutations.solve(new StringBuilder(string), 0, result);
26 | return result;
27 | }
28 |
29 | public static void main(String[] args) {
30 | String string = "ABC";
31 | List result = StringPermutations.permute(string);
32 | for(String s : result) {
33 | System.out.print(s + " ");
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/backtracking/Subset.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/backtracking/Subset.class
--------------------------------------------------------------------------------
/src/backtracking/Subset.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class Subset {
4 |
5 | // public static void solve(int index, int[] nums, List subset, List> powerSet) {
6 |
7 | // if(index == nums.length) {
8 | // powerSet.add(new ArrayList<>(subset));
9 | // return;
10 | // }
11 |
12 | // // include
13 | // subset.add(nums[index]);
14 | // solve(index + 1, nums, subset, powerSet);
15 | // subset.remove(subset.size() - 1);
16 |
17 | // // exclude
18 | // while(index < (nums.length - 1) && nums[index] == nums[index + 1]) {
19 | // index += 1;
20 | // }
21 | // solve(index + 1, nums, subset, powerSet);
22 | // }
23 |
24 | public static void solve(int index, int[] nums, List subset, List> powerSet) {
25 | powerSet.add(new ArrayList<>(subset));
26 | for(int i = index; i < nums.length; i++) {
27 | if(i != index && nums[i] == nums[i - 1]) continue;
28 | subset.add(nums[i]);
29 | solve(i + 1, nums, subset, powerSet);
30 | subset.remove(subset.size() - 1);
31 | }
32 | }
33 |
34 |
35 | public static List> subsets(int[] nums) {
36 | List> powerSet = new ArrayList<>();
37 | List subset = new ArrayList<>();
38 | Arrays.sort(nums);
39 | solve(0, nums, subset, powerSet);
40 | return powerSet;
41 | }
42 |
43 | public static void main(String[] args) {
44 | int[] nums = new int[]{1, 1, 2};
45 | List> ans = Subset.subsets(nums);
46 | System.out.println(ans);
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/src/dynamicprogramming/memoization/ClimbingStairs.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/dynamicprogramming/memoization/ClimbingStairs.class
--------------------------------------------------------------------------------
/src/dynamicprogramming/memoization/ClimbingStairs.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class ClimbingStairs {
4 |
5 | public static int findWays(int n, int dp[]) {
6 | if(n == 0) {
7 | dp[n] = 1;
8 | return dp[n];
9 | }
10 | if(n < 0) {
11 | return 0;
12 | }
13 | if(dp[n] != -1) {
14 | return dp[n];
15 | }
16 | int right = ClimbingStairs.findWays(n - 1, dp);
17 | int left = ClimbingStairs.findWays(n - 2, dp);
18 |
19 | dp[n] = left + right;
20 | return dp[n];
21 | }
22 |
23 | public static void main(String[] args) {
24 | int n = 10000;
25 | int dp[] = new int[n + 1];
26 | Arrays.fill(dp, -1);
27 | long start = System.currentTimeMillis();
28 | System.out.println(ClimbingStairs.findWays(n, dp));
29 | long end = System.currentTimeMillis();
30 | System.out.println(end - start);
31 | }
32 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/memoization/Knapsack.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/dynamicprogramming/memoization/Knapsack.class
--------------------------------------------------------------------------------
/src/dynamicprogramming/memoization/Knapsack.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 |
3 | class Knapsack {
4 |
5 | public static int solve(int wt[], int val[], int C, int n, int dp[][]) {
6 | if(n == 0 || C == 0) {
7 | dp[n][C] = 0;
8 | return 0;
9 | }
10 |
11 | if(wt[n - 1] > C) {
12 | dp[n][C] = solve(wt, val, C, n - 1, dp);
13 | return dp[n][C];
14 | }
15 |
16 | dp[n][C] = Math.max(val[n - 1] + solve(wt, val, C - wt[n - 1], n - 1, dp),
17 | solve(wt, val, C, n - 1, dp));
18 | return dp[n][C];
19 | }
20 |
21 | public static int maxProfit(int wt[], int val[], int C) {
22 | int dp[][] = new int[wt.length + 1][C + 1];
23 | for(int arr[] : dp) {
24 | Arrays.fill(arr, - 1);
25 | }
26 | return Knapsack.solve(wt, val, C, wt.length, dp);
27 | }
28 | public static void main(String[] args) {
29 | int wt[] = {1, 2, 3, 4, 8};
30 | int val[] = {2, 3, 3, 2, 10};
31 | int C = 7;
32 | int profit = Knapsack.maxProfit(wt, val, C);
33 | System.out.println(profit);
34 | }
35 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/memoization/LongestCommonSubsequence.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/dynamicprogramming/memoization/LongestCommonSubsequence.class
--------------------------------------------------------------------------------
/src/dynamicprogramming/memoization/LongestCommonSubsequence.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class LongestCommonSubsequence {
4 |
5 | public static int solve(String a, String b, int m, int n, int dp[][]) {
6 | if(m == 0 || n == 0) return 0;
7 |
8 | if(dp[m][n] != -1) return dp[m][n];
9 |
10 | if(a.charAt(m - 1) == b.charAt(n - 1)) {
11 | dp[m][n] = 1 + LongestCommonSubsequence.solve(a, b, m - 1, n - 1, dp);
12 | return dp[m][n];
13 | }
14 |
15 | int left = LongestCommonSubsequence.solve(a, b, m - 1, n, dp);
16 | int right = LongestCommonSubsequence.solve(a, b, m, n - 1, dp);
17 |
18 | dp[m][n] = Math.max(left, right);
19 | return dp[m][n];
20 | }
21 |
22 | public static int longestCommonSubsequence(String a, String b) {
23 | int m = a.length();
24 | int n = b.length();
25 | int dp[][] = new int[m + 1][n + 1];
26 | for(int arr[] : dp) {
27 | Arrays.fill(arr, -1);
28 | }
29 | return solve(a, b, m, n, dp);
30 | }
31 |
32 | public static void main(String[] args) {
33 | String a = "abcd";
34 | String b = "bcad";
35 | int lcs = LongestCommonSubsequence.longestCommonSubsequence(a, b);
36 | System.out.println(lcs);
37 | }
38 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/memoization/UnboundedKnapsack.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/dynamicprogramming/memoization/UnboundedKnapsack.class
--------------------------------------------------------------------------------
/src/dynamicprogramming/memoization/UnboundedKnapsack.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 |
3 | class UnboundedKnapsack {
4 |
5 | public static int solve(int wt[], int val[], int C, int n, int dp[][]) {
6 | if(n == 0 || C == 0) {
7 | dp[n][C] = 0;
8 | return 0;
9 | }
10 |
11 | if(wt[n - 1] > C) {
12 | dp[n][C] = solve(wt, val, C, n - 1, dp);
13 | return dp[n][C];
14 | }
15 |
16 | dp[n][C] = Math.max(val[n - 1] + solve(wt, val, C - wt[n - 1], n, dp),
17 | solve(wt, val, C, n - 1, dp));
18 | return dp[n][C];
19 | }
20 |
21 | public static int maxProfit(int wt[], int val[], int C) {
22 | int dp[][] = new int[wt.length + 1][C + 1];
23 | for(int arr[] : dp) {
24 | Arrays.fill(arr, - 1);
25 | }
26 | return UnboundedKnapsack.solve(wt, val, C, wt.length, dp);
27 | }
28 | public static void main(String[] args) {
29 | int wt[] = {1, 2, 3, 4, 8};
30 | int val[] = {2, 3, 3, 2, 10};
31 | int C = 7;
32 | int profit = UnboundedKnapsack.maxProfit(wt, val, C);
33 | System.out.println(profit);
34 | }
35 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/tabulation/Base.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/dynamicprogramming/tabulation/Base.class
--------------------------------------------------------------------------------
/src/dynamicprogramming/tabulation/ClimbingStairs.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/dynamicprogramming/tabulation/ClimbingStairs.class
--------------------------------------------------------------------------------
/src/dynamicprogramming/tabulation/ClimbingStairs.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class ClimbingStairs {
4 |
5 | public static int findWays(int n) {
6 | if(n == 1) return 1;
7 | int dp[] = new int[n + 1];
8 | dp[1] = 1;
9 | dp[2] = 2;
10 | for(int i = 3; i <= n; i++) {
11 | dp[i] = dp[i - 1] + dp[i - 2];
12 | }
13 | return dp[n];
14 | }
15 |
16 | public static void main(String[] args) {
17 | int n = 20;
18 | System.out.println(ClimbingStairs.findWays(n));
19 | }
20 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/tabulation/Derived.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/dynamicprogramming/tabulation/Derived.class
--------------------------------------------------------------------------------
/src/dynamicprogramming/tabulation/Knapsack.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/dynamicprogramming/tabulation/Knapsack.class
--------------------------------------------------------------------------------
/src/dynamicprogramming/tabulation/Knapsack.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 |
3 | class Knapsack {
4 |
5 | public static int maxProfit(int wt[], int val[], int C) {
6 | int n = wt.length;
7 | int dp[][] = new int[n + 1][C + 1];
8 | for(int i = 0; i < dp.length; i++) {
9 | for(int j = 0; j < dp[0].length; j++) {
10 | if(i == 0 || j == 0) {
11 | dp[i][j] = 0;
12 | } else if(wt[i - 1] > j) {
13 | dp[i][j] = dp[i - 1][j];
14 | } else {
15 | dp[i][j] = Math.max(val[i - 1] + dp[i - 1][j - wt[i - 1]], dp[i - 1][j]);
16 | }
17 | }
18 | }
19 | return dp[n][C];
20 | }
21 | public static void main(String[] args) {
22 | int wt[] = {1, 2, 3, 4, 8};
23 | int val[] = {2, 3, 3, 2, 10};
24 | int C = 7;
25 | int profit = Knapsack.maxProfit(wt, val, C);
26 | System.out.println(profit);
27 | }
28 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/tabulation/LongestCommonSubsequence.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/dynamicprogramming/tabulation/LongestCommonSubsequence.class
--------------------------------------------------------------------------------
/src/dynamicprogramming/tabulation/LongestCommonSubsequence.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class LongestCommonSubsequence {
4 |
5 | public static int longestCommonSubsequence(String a, String b) {
6 | int m = a.length();
7 | int n = b.length();
8 |
9 | int dp[][] = new int[m + 1][n + 1];
10 |
11 | for(int i = 0; i <= m; i++) {
12 | for(int j = 0; j <= n; j++) {
13 | if(i == 0 || j == 0) {
14 | dp[i][j] = 0;
15 | } else if(a.charAt(i - 1) == b.charAt(j - 1)) {
16 | dp[i][j] = 1 + dp[i - 1][j - 1];
17 | } else {
18 | dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
19 | }
20 | }
21 | }
22 |
23 | return dp[m][n];
24 | }
25 |
26 | public static void main(String[] args) {
27 | String a = "abcd";
28 | String b = "bcad";
29 | int lcs = LongestCommonSubsequence.longestCommonSubsequence(a, b);
30 | System.out.println(lcs);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/dynamicprogramming/tabulation/UnboundedKnapsack.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/dynamicprogramming/tabulation/UnboundedKnapsack.class
--------------------------------------------------------------------------------
/src/dynamicprogramming/tabulation/UnboundedKnapsack.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 |
3 | class UnboundedKnapsack {
4 |
5 | public static int maxProfit(int wt[], int val[], int C) {
6 | int n = wt.length;
7 | int dp[][] = new int[n + 1][C + 1];
8 | for(int i = 0; i < dp.length; i++) {
9 | for(int j = 0; j < dp[0].length; j++) {
10 | if(i == 0 || j == 0) {
11 | dp[i][j] = 0;
12 | } else if(wt[i - 1] > j) {
13 | dp[i][j] = dp[i - 1][j];
14 | } else {
15 | dp[i][j] = Math.max(val[i - 1] + dp[i][j - wt[i - 1]], dp[i - 1][j]);
16 | }
17 | }
18 | }
19 | return dp[n][C];
20 | }
21 | public static void main(String[] args) {
22 | int wt[] = {1, 2, 3, 4, 8};
23 | int val[] = {2, 3, 3, 2, 10};
24 | int C = 7;
25 | int profit = UnboundedKnapsack.maxProfit(wt, val, C);
26 | System.out.println(profit);
27 | }
28 | }
--------------------------------------------------------------------------------
/src/graph/AdjacencyList.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class AdjacencyList {
4 |
5 | public static List> buildGraph(int v, int[][] edges) {
6 | List> graph = new ArrayList<>();
7 | for(int i = 0; i <= v; i++) {
8 | graph.add(new ArrayList<>());
9 | }
10 |
11 | for(int[] edge : edges) {
12 | graph.get(edge[0]).add(edge[1]);
13 | graph.get(edge[1]).add(edge[0]); // remove if directed
14 | }
15 | return graph;
16 | }
17 |
18 | public static void printGraph(int v, int[][] edges) {
19 | List> graph = AdjacencyList.buildGraph(v, edges);
20 | for(int i = 1; i <= v; i++) {
21 | System.out.print(i + " : ");
22 | for(int nbr : graph.get(i)) {
23 | System.out.print(nbr + " ");
24 | }
25 | System.out.println();
26 | }
27 | }
28 |
29 | public static List breadthFirstSearch(int v, int[][] edges, int src) {
30 | List> graph = AdjacencyList.buildGraph(v, edges);
31 |
32 | boolean[] visited = new boolean[v + 1];
33 | Queue queue = new LinkedList();
34 | queue.offer(src);
35 | visited[src] = true;
36 |
37 | List bfs = new ArrayList<>();
38 |
39 | while(!queue.isEmpty()) {
40 | int node = queue.poll();
41 | bfs.add(node);
42 | for(int nbr : graph.get(node)) {
43 | if(!visited[nbr]) {
44 | queue.offer(nbr);
45 | visited[nbr] = true;
46 | }
47 | }
48 | }
49 | return bfs;
50 |
51 | }
52 |
53 | public static void main(String[] args) {
54 | int v = 6;
55 | int[][] edges = new int[][]{{1, 2}, {1, 5}, {2, 3}, {2, 4}, {3, 4}, {3, 6}, {4, 6}, {5, 6}};
56 | AdjacencyList.printGraph(v, edges);
57 | System.out.println(AdjacencyList.breadthFirstSearch(v, edges, 1));
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/src/graph/AdjacencyMatrix.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class AdjacencyMatrix {
4 |
5 | public static boolean[][] buildGraph(int v, int[][] edges) {
6 | boolean[][] graph = new boolean[v + 1][v + 1];
7 |
8 | for(int[] edge : edges) {
9 | graph[edge[0]][edge[1]] = true;
10 | graph[edge[1]][edge[0]] = true; // remove if directed
11 | }
12 | return graph;
13 | }
14 |
15 | public static void printGraph(int v, int[][] edges) {
16 | boolean[][] graph = AdjacencyMatrix.buildGraph(v, edges);
17 | for(int i = 1; i <= v; i++) {
18 | System.out.print(i + " : ");
19 | for(int j = 1; j <= v; j++) {
20 | if(graph[i][j])
21 | System.out.print(j + " ");
22 | }
23 | System.out.println();
24 | }
25 | }
26 |
27 | public static void main(String[] args) {
28 | int v = 5;
29 | int[][] edges = new int[][]{{1, 2}, {1, 4}, {1, 5}, {2, 3}, {2, 5}, {3, 5}};
30 | AdjacencyMatrix.printGraph(v, edges);
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/graph/AlienDictionary.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/graph/AlienDictionary.class
--------------------------------------------------------------------------------
/src/graph/AlienDictionary.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class AlienDictionary {
4 | public static void buildGraph(int n, int k, String[] words, Map> graph, Map indegree) {
5 | for(char i = 'a'; i < 'a' + k; i++) {
6 | graph.put(i, new ArrayList<>());
7 | indegree.put(i, 0);
8 | }
9 |
10 | for(int i = 0; i < words.length - 1; i++) {
11 | String currWord = words[i];
12 | String nextWord = words[i + 1];
13 | for(int j = 0; j < Math.min(currWord.length(), nextWord.length()); j++) {
14 | if(currWord.charAt(j) != nextWord.charAt(j)) {
15 | graph.get(currWord.charAt(j)).add(nextWord.charAt(j));
16 | indegree.put(nextWord.charAt(j), indegree.get(nextWord.charAt(j)) + 1);
17 | break;
18 | }
19 | }
20 | }
21 | }
22 |
23 | public static String findOrder(int n, int k, String[] words) {
24 | Map> graph = new HashMap<>();
25 | Map indegree = new HashMap<>();
26 | AlienDictionary.buildGraph(n, k, words, graph, indegree);
27 |
28 | Queue queue = new LinkedList<>();
29 | for(Map.Entry entry : indegree.entrySet()) {
30 | if(entry.getValue() == 0) {
31 | queue.offer(entry.getKey());
32 | }
33 | }
34 | StringBuilder sortedOrder = new StringBuilder();
35 | while(!queue.isEmpty()) {
36 | char currNode = queue.poll();
37 | sortedOrder.append(currNode);
38 |
39 | for(char nbr : graph.get(currNode)) {
40 | indegree.put(nbr, indegree.get(nbr) - 1);
41 | if(indegree.get(nbr) == 0) {
42 | queue.offer(nbr);
43 | }
44 | }
45 | }
46 | return sortedOrder.length() == k ? sortedOrder.toString() : "";
47 | }
48 |
49 | public static void main(String[] args) {
50 | int n = 5;
51 | int k = 4;
52 | String words[] = { "baa", "abcd", "abca", "cab", "cad"};
53 | System.out.println(AlienDictionary.findOrder(n, k, words));
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/graph/CountNodesInDisconnectedComponents.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class CountNodesInDisconnectedComponents {
4 |
5 | public static List> buildGraph(int v, int[][] edges) {
6 | List> graph = new ArrayList<>();
7 | for(int i = 0; i <= v; i++) {
8 | graph.add(new ArrayList<>());
9 | }
10 |
11 | for(int[] edge : edges) {
12 | graph.get(edge[0]).add(edge[1]);
13 | graph.get(edge[1]).add(edge[0]); // remove if directed
14 | }
15 | return graph;
16 | }
17 |
18 | public static int dfs(int node, boolean[] visited, List> graph) {
19 | visited[node] = true;
20 | int c = 1;
21 | for(int nbr : graph.get(node)) {
22 | if(!visited[nbr]) {
23 | c += dfs(nbr, visited, graph);
24 | }
25 | }
26 | return c;
27 | }
28 |
29 | public static List disconnectedComponents(int v, int[][] edges) {
30 | List> graph = CountNodesInDisconnectedComponents.buildGraph(v, edges);
31 | boolean[] visited = new boolean[v + 1];
32 | List connectedCount = new ArrayList<>();
33 | for(int i = 1; i <= v; i++) {
34 | if(!visited[i]) {
35 | int c = CountNodesInDisconnectedComponents.dfs(i, visited, graph);
36 | connectedCount.add(c);
37 | }
38 |
39 | }
40 | return connectedCount;
41 | }
42 | public static void main(String[] args) {
43 | int v = 5;
44 | int[][] edges = new int[][]{{1, 2}, {1, 3}, {1, 4}};
45 | System.out.println(CountNodesInDisconnectedComponents.disconnectedComponents(v, edges));
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/graph/CourseSchedule.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/graph/CourseSchedule.class
--------------------------------------------------------------------------------
/src/graph/CourseSchedule.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class CourseSchedule {
4 | public static void buildGraph(int v, int[][] edges, List> graph, Map indegree) {
5 | for(int i = 0; i < v; i++) {
6 | graph.add(new ArrayList<>());
7 | indegree.put(i, 0);
8 | }
9 |
10 | for(int[] edge : edges) {
11 | graph.get(edge[0]).add(edge[1]);
12 | indegree.put(edge[1], indegree.get(edge[1]) + 1);
13 | }
14 | }
15 |
16 | public static boolean canBeDone(int v, int[][] edges) {
17 | List> graph = new ArrayList<>();
18 | Map indegree = new HashMap<>();
19 | CourseSchedule.buildGraph(v, edges, graph, indegree);
20 |
21 | Queue queue = new LinkedList<>();
22 |
23 | for(Map.Entry entry : indegree.entrySet()) {
24 | if(entry.getValue() == 0) {
25 | queue.offer(entry.getKey());
26 | }
27 | }
28 | List sortedOrder = new ArrayList<>();
29 | while(!queue.isEmpty()) {
30 | int currNode = queue.poll();
31 | sortedOrder.add(currNode);
32 |
33 | for(int nbr : graph.get(currNode)) {
34 | indegree.put(nbr, indegree.get(nbr) - 1);
35 | if(indegree.get(nbr) == 0) {
36 | queue.offer(nbr);
37 | }
38 | }
39 | }
40 | return sortedOrder.size() == v ? true : false;
41 | }
42 |
43 | public static void main(String[] args) {
44 | int v = 7;
45 | int[][] edges = new int[][]{{5, 1}, {5, 2}, {6, 2}, {6, 3}, {1, 4}, {2, 0}, {3, 0}};
46 | System.out.println(CourseSchedule.canBeDone(v, edges));
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/graph/CriticalEdgesPseudoCriticalEdges.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public void union(int u, int v, int[] parent) {
3 | int pu = find(u, parent);
4 | int pv = find(v, parent);
5 | if(pu != pv) {
6 | parent[pv] = pu;
7 | }
8 | }
9 |
10 | public int find(int node, int[] parent) {
11 | if(parent[node] == node) {
12 | return node;
13 | }
14 | return find(parent[node], parent);
15 | }
16 |
17 | public int mst(int n, int[][] edges, int includeEdge[], int excludeEdge[]) {
18 |
19 | int[] parent = new int[n];
20 | for(int i = 0; i < n; i++) {
21 | parent[i] = i;
22 | }
23 | int ans = 0;
24 | int size = 0;
25 | if(includeEdge != null) {
26 | int parent1 = find(includeEdge[0], parent);
27 | int parent2 = find(includeEdge[1], parent);
28 | union(parent1, parent2, parent);
29 | ans += includeEdge[2];
30 | size += 1;
31 | }
32 |
33 | for(int[] edge : edges) {
34 | if(excludeEdge != null && edge[0] == excludeEdge[0] && edge[1] == excludeEdge[1] && edge[2] == excludeEdge[2]) {
35 | continue;
36 | }
37 | if(includeEdge != null && edge[0] == includeEdge[0] && edge[1] == includeEdge[1] && edge[2] == includeEdge[2]) {
38 | continue;
39 | }
40 | int u = edge[0];
41 | int v = edge[1];
42 | int cost = edge[2];
43 | int p1 = find(u, parent);
44 | int p2 = find(v, parent);
45 | if(p1 != p2) {
46 | union(p1, p2, parent);
47 | ans += cost;
48 | size += 1;
49 | }
50 | }
51 |
52 | return (size == n - 1) ? ans : Integer.MAX_VALUE;
53 | }
54 |
55 | public List> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) {
56 | int originalEdges[][] = new int[edges.length][3];
57 | for(int i = 0; i < edges.length; i++) {
58 | originalEdges[i][0] = edges[i][0];
59 | originalEdges[i][1] = edges[i][1];
60 | originalEdges[i][2] = edges[i][2];
61 | }
62 | List> result = new ArrayList<>();
63 | List criticalEdges = new ArrayList<>();
64 | List pseudoCriticalEdges = new ArrayList<>();
65 | Arrays.sort(edges, (a, b) -> a[2] - b[2]);
66 | int originalCost = mst(n, edges, null, null);
67 | for(int i = 0; i < originalEdges.length; i++) {
68 | int excludedCost = mst(n, edges, null, originalEdges[i]);
69 | int includedCost = mst(n, edges, originalEdges[i], null);
70 | if(excludedCost > originalCost) {
71 | criticalEdges.add(i);
72 | } else if(includedCost == originalCost) {
73 | pseudoCriticalEdges.add(i);
74 | }
75 | }
76 | result.add(criticalEdges);
77 | result.add(pseudoCriticalEdges);
78 | return result;
79 | }
80 | }
--------------------------------------------------------------------------------
/src/graph/DSU.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/graph/DSU.class
--------------------------------------------------------------------------------
/src/graph/DSU.java:
--------------------------------------------------------------------------------
1 | public class DSU {
2 |
3 | public static void union(int u, int v, int[] parent) {
4 | int pu = find(u, parent);
5 | int pv = find(v, parent);
6 | if(pu != pv) {
7 | parent[pv] = pu;
8 | }
9 | }
10 |
11 | public static int find(int node, int[] parent) {
12 | if(parent[node] == node) {
13 | return node;
14 | }
15 | return find(parent[node], parent);
16 | }
17 |
18 | public static int[] connectedComponents(int n, int[][] edges) {
19 |
20 | int[] parent = new int[n];
21 | for(int i = 0; i < n; i++) {
22 | parent[i] = i;
23 | }
24 |
25 | for(int[] edge : edges) {
26 | DSU.union(edge[0], edge[1], parent);
27 | }
28 |
29 | return parent;
30 | }
31 | public static void main(String[] args) {
32 | int[][] edges = new int[][]{{0, 1}, {1, 2}, {1, 3}, {1, 4}, {2, 4}, {5, 6}, {6, 7}, {7, 8}, {3, 7}};
33 | int n = 9;
34 | int ans[] = DSU.connectedComponents(n, edges);
35 | for(int i = 0; i < n; i++) {
36 | System.out.println(ans[i] + " is parent if " + i);
37 | }
38 | System.out.println(find(8, ans));
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/graph/DepthFirstSearch.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class DepthFirstSearch {
4 |
5 | public static List> buildGraph(int v, int[][] edges) {
6 | List> graph = new ArrayList<>();
7 | for(int i = 0; i < v; i++) {
8 | graph.add(new ArrayList<>());
9 | }
10 |
11 | for(int[] edge : edges) {
12 | graph.get(edge[0]).add(edge[1]);
13 | graph.get(edge[1]).add(edge[0]); // remove if directed
14 | }
15 | return graph;
16 | }
17 |
18 | public static void dfs(int node, boolean[] visited, List> graph, List dfs) {
19 | visited[node] = true;
20 | dfs.add(node);
21 | for(int nbr : graph.get(node)) {
22 | if(!visited[nbr]) {
23 | dfs(nbr, visited, graph, dfs);
24 | }
25 | }
26 | }
27 |
28 | public static int[] depthFirstSearch(int v, int[][] edges, int src) {
29 | List> graph = DepthFirstSearch.buildGraph(v, edges);
30 | boolean[] visited = new boolean[v];
31 | List dfs = new ArrayList<>();
32 | DepthFirstSearch.dfs(src, visited, graph, dfs);
33 | // for(int i = 1; i <= v; i++) {
34 | // if(!visited[i])
35 | // DepthFirstSearch.dfs(i, visited, graph, dfs);
36 | // }
37 | int ans[] = new int[v];
38 | for(int i = 0; i < v; i++) {
39 | ans[i] = dfs.get(i);
40 | }
41 | return ans;
42 | }
43 | public static void main(String[] args) {
44 | int v = 6;
45 | int[][] edges = new int[][]{{0, 1}, {0, 2}, {0, 5}, {1, 3}, {1, 5}, {2, 3}, {3, 4}, {4, 5}};
46 | int src = 0;
47 | for(int a : DepthFirstSearch.depthFirstSearch(v, edges, src)) {
48 | System.out.print(a + " ");
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/graph/DijkstraAlgorithm.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/graph/DijkstraAlgorithm.class
--------------------------------------------------------------------------------
/src/graph/DijkstraAlgorithm.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class Pair {
4 | int node, distance;
5 | public Pair(int node, int distance) {
6 | this.node = node;
7 | this.distance = distance;
8 | }
9 | }
10 |
11 | class DijkstraAlgorithm {
12 |
13 | public static List> buildGraph(int edges[][], int nodes) {
14 |
15 | List> graph = new ArrayList<>();
16 | for(int i = 0; i < nodes; i++) {
17 | graph.add(new ArrayList<>());
18 | }
19 | for(int edge[] : edges) {
20 | graph.get(edge[0]).add(new Pair(edge[1], edge[2]));
21 | graph.get(edge[1]).add(new Pair(edge[0], edge[2]));
22 | }
23 | for(int i = 0; i < nodes; i++) {
24 | System.out.println(i + " : " + graph.get(i));
25 | }
26 | return graph;
27 | }
28 |
29 | public static int[] shortestPath(int edges[][], int nodes, int src) {
30 | List> graph = DijkstraAlgorithm.buildGraph(edges, nodes);
31 | PriorityQueue minHeap = new PriorityQueue<>((p1, p2) -> p1.distance - p2.distance);
32 |
33 | boolean visited[] = new boolean[nodes];
34 | int distance[] = new int[nodes];
35 | Arrays.fill(distance, Integer.MAX_VALUE);
36 |
37 | distance[src] = 0;
38 | minHeap.offer(new Pair(src, distance[src]));
39 |
40 | while(!minHeap.isEmpty()) {
41 | Pair pair = minHeap.poll();
42 | int currNode = pair.node;
43 | int currDistance = pair.distance;
44 |
45 | if(visited[currNode]) continue;
46 |
47 | visited[currNode] = true;
48 |
49 | for(Pair nbrPair : graph.get(currNode)) {
50 | if(visited[nbrPair.node]) continue;
51 | int newDistance = currDistance + nbrPair.distance;
52 | if(newDistance < distance[nbrPair.node]) {
53 | distance[nbrPair.node] = newDistance;
54 | minHeap.offer(new Pair(nbrPair.node, distance[nbrPair.node]));
55 | }
56 | }
57 |
58 | }
59 | return distance;
60 | }
61 |
62 | public static void main(String[] args) {
63 | int edges[][] = new int[][] {{0, 1, 2}, {0, 2, 9}, {0, 3, 8}, {1, 2, 5}, {1, 4, 2}, {2, 3, 1}, {3, 4, 1}};
64 |
65 | int vertices = 5;
66 | int distance[] = shortestPath(edges, vertices, 0);
67 | for(int dist : distance) {
68 | System.out.print(dist + " ");
69 | }
70 | }
71 | }
--------------------------------------------------------------------------------
/src/graph/DisconnectedComponents.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class DisconnectedComponents {
4 |
5 | public static List> buildGraph(int v, int[][] edges) {
6 | List> graph = new ArrayList<>();
7 | for(int i = 0; i <= v; i++) {
8 | graph.add(new ArrayList<>());
9 | }
10 |
11 | for(int[] edge : edges) {
12 | graph.get(edge[0]).add(edge[1]);
13 | graph.get(edge[1]).add(edge[0]); // remove if directed
14 | }
15 | return graph;
16 | }
17 |
18 | public static void dfs(int node, boolean[] visited, List> graph, List dfs) {
19 | visited[node] = true;
20 | dfs.add(node);
21 | for(int nbr : graph.get(node)) {
22 | if(!visited[nbr]) {
23 | dfs(nbr, visited, graph, dfs);
24 | }
25 | }
26 | }
27 |
28 | public static List> disconnectedComponents(int v, int[][] edges) {
29 | List> graph = DisconnectedComponents.buildGraph(v, edges);
30 | boolean[] visited = new boolean[v + 1];
31 | List> components = new ArrayList<>();
32 | for(int i = 1; i <= v; i++) {
33 | if(!visited[i]) {
34 | List dfs = new ArrayList<>();
35 | DisconnectedComponents.dfs(i, visited, graph, dfs);
36 | components.add(dfs);
37 | }
38 |
39 | }
40 | return components;
41 | }
42 | public static void main(String[] args) {
43 | int v = 9;
44 | int[][] edges = new int[][]{{1, 2}, {1, 5}, {2, 3}, {3, 7}, {4, 6}, {4, 7}, {5, 6}, {5, 7}, {8, 9}};
45 | System.out.println(DisconnectedComponents.disconnectedComponents(v, edges));
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/graph/KruskalsAlgo.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/graph/KruskalsAlgo.class
--------------------------------------------------------------------------------
/src/graph/KruskalsAlgo.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class KruskalsAlgo {
4 |
5 | public static void union(int u, int v, int[] parent) {
6 | int pu = find(u, parent);
7 | int pv = find(v, parent);
8 | if(pu != pv) {
9 | parent[pv] = pu;
10 | }
11 | }
12 |
13 | public static int find(int node, int[] parent) {
14 | if(parent[node] == node) {
15 | return node;
16 | }
17 | return find(parent[node], parent);
18 | }
19 |
20 | public static int mst(int n, int[][] edges) {
21 | Arrays.sort(edges, (a, b) -> a[2] - b[2]);
22 |
23 | int[] parent = new int[n];
24 | for(int i = 0; i < n; i++) {
25 | parent[i] = i;
26 | }
27 | int ans = 0;
28 | for(int[] edge : edges) {
29 | int u = edge[0];
30 | int v = edge[1];
31 | int cost = edge[2];
32 | int p1 = KruskalsAlgo.find(u, parent);
33 | int p2 = KruskalsAlgo.find(v, parent);
34 | if(p1 != p2) {
35 | KruskalsAlgo.union(p1, p2, parent);
36 | ans += cost;
37 | }
38 | }
39 |
40 | return ans;
41 | }
42 | public static void main(String[] args) {
43 | int[][] edges = new int[][]{{0, 1, 8}, {0, 2, 2}, {1, 4, 1}, {1, 5, 3}, {2, 3, 6}, {2, 4, 3}, {3, 5, 4}, {4, 5, 2}};
44 | int n = 6;
45 | int ans = KruskalsAlgo.mst(n, edges);
46 | System.out.println(ans);
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/graph/MinCostToConnectAllPoints.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class Pair {
4 | int node, distance;
5 | public Pair(int node, int distance) {
6 | this.node = node;
7 | this.distance = distance;
8 | }
9 | }
10 |
11 | class Solution {
12 | private List> buildGraph(int n, int[][] edges) {
13 | List> graph = new ArrayList<>();
14 | for(int i = 0; i < n; i++) {
15 | graph.add(new ArrayList<>());
16 | }
17 | for(int[] edge : edges) {
18 | graph.get(edge[0]).add(new Pair(edge[1], edge[2]));
19 | graph.get(edge[1]).add(new Pair(edge[0], edge[2]));
20 | }
21 | return graph;
22 | }
23 |
24 | private int findMinCost(int n, int[][] edges) {
25 | List> graph = buildGraph(n, edges);
26 | PriorityQueue minHeap = new PriorityQueue<>((p1, p2) -> (p1.distance - p2.distance));
27 |
28 | boolean[] mstSet = new boolean[n + 1];
29 | int[] distance = new int[n + 1];
30 | Arrays.fill(distance, Integer.MAX_VALUE);
31 |
32 | distance[0] = 0;
33 | minHeap.offer(new Pair(0, distance[0]));
34 |
35 | while(!minHeap.isEmpty()) {
36 | Pair pair = minHeap.poll();
37 | int currNode = pair.node;
38 |
39 | if(mstSet[currNode]) continue;
40 |
41 | mstSet[currNode] = true;
42 |
43 | for(Pair nbrPair : graph.get(currNode)) {
44 | int nbrNode = nbrPair.node;
45 | int nbrDistance = nbrPair.distance;
46 |
47 | if(!mstSet[nbrNode] && nbrDistance < distance[nbrNode]) {
48 | distance[nbrNode] = nbrDistance;
49 | minHeap.offer(nbrPair);
50 | }
51 | }
52 | }
53 | int minCost = 0;
54 | for(int i = 0; i < n; i++) {
55 | minCost += distance[i];
56 | }
57 | return minCost ;
58 | }
59 |
60 | public int minCostConnectPoints(int[][] points) {
61 | int[][] edges = new int[(points.length * (points.length - 1))/ 2][3];
62 | int k = 0;
63 | for(int i = 0; i < points.length - 1; i++) {
64 | for(int j = i + 1; j < points.length; j++) {
65 | edges[k][0] = i;
66 | edges[k][1] = j;
67 | edges[k][2] = Math.abs(points[j][0] - points[i][0]) + Math.abs(points[j][1] - points[i][1]);
68 | k += 1;
69 | }
70 | }
71 | return findMinCost(points.length, edges);
72 |
73 | }
74 | }
--------------------------------------------------------------------------------
/src/graph/Pair.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/graph/Pair.class
--------------------------------------------------------------------------------
/src/graph/PrimsAlgorithm.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/graph/PrimsAlgorithm.class
--------------------------------------------------------------------------------
/src/graph/PrimsAlgorithm.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class Pair {
4 | int node, distance;
5 | public Pair(int node, int distance) {
6 | this.node = node;
7 | this.distance = distance;
8 | }
9 | }
10 |
11 | class PrimsAlgorithm {
12 |
13 | private static List> buildGraph(int n, int[][] edges) {
14 | List> graph = new ArrayList<>();
15 | for(int i = 0; i <= n; i++) {
16 | graph.add(new ArrayList<>());
17 | }
18 | for(int[] edge : edges) {
19 | graph.get(edge[0]).add(new Pair(edge[1], edge[2]));
20 | graph.get(edge[1]).add(new Pair(edge[0], edge[2]));
21 | }
22 | return graph;
23 | }
24 |
25 | private static int findMST(int n, int[][] edges) {
26 | List> graph = PrimsAlgorithm.buildGraph(n, edges);
27 | PriorityQueue minHeap = new PriorityQueue<>((p1, p2) -> (p1.distance - p2.distance));
28 |
29 | boolean[] mstSet = new boolean[n + 1];
30 | int[] distance = new int[n + 1];
31 | Arrays.fill(distance, Integer.MAX_VALUE);
32 | int[] parent = new int[n + 1];
33 |
34 | distance[1] = 0;
35 | parent[1] = -1;
36 | minHeap.offer(new Pair(1, distance[1]));
37 |
38 | while(!minHeap.isEmpty()) {
39 | Pair pair = minHeap.poll();
40 | int currNode = pair.node;
41 |
42 | if(mstSet[currNode]) continue;
43 |
44 | mstSet[currNode] = true;
45 |
46 | for(Pair nbrPair : graph.get(currNode)) {
47 | int nbrNode = nbrPair.node;
48 | int nbrDistance = nbrPair.distance;
49 |
50 | if(!mstSet[nbrNode] && nbrDistance < distance[nbrNode]) {
51 | distance[nbrNode] = nbrDistance;
52 | parent[nbrNode] = currNode;
53 | minHeap.offer(nbrPair);
54 | }
55 | }
56 | }
57 | int minCost = 0;
58 | for(int i = 1; i <= n; i++) {
59 | minCost += distance[i];
60 | }
61 | return minCost ;
62 | }
63 |
64 | public static void main(String[] args) {
65 | int[][] edges = new int[][]{{1, 2, 1}, {1, 3, 6}, {2, 4, 3}, {2, 6, 5}, {3, 5, 2}, {3, 6, 8}, {4, 8, 7}, {5, 6, 3}, {5, 7, 2}, {7, 8, 9}, {7, 9, 4}, {8, 9, 3}};
66 | int nodes = 9;
67 | int cost = PrimsAlgorithm.findMST(nodes, edges);
68 | System.out.println(cost);
69 | }
70 | }
--------------------------------------------------------------------------------
/src/graph/RoadsAndLibraries.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class RoadsAndLibraries {
4 |
5 | public static List> buildGraph(int n, List> edges) {
6 | List> graph = new ArrayList<>();
7 | for(int i = 0; i <= n; i++) {
8 | graph.add(new ArrayList<>());
9 | }
10 |
11 | for(List edge : edges) {
12 | graph.get(edge.get(0)).add(edge.get(1));
13 | graph.get(edge.get(1)).add(edge.get(0)); // remove if directed
14 | }
15 | return graph;
16 | }
17 |
18 | public static int dfs(int node, boolean[] visited, List> graph) {
19 | visited[node] = true;
20 | int c = 1;
21 | for(int nbr : graph.get(node)) {
22 | if(!visited[nbr]) {
23 | c += dfs(nbr, visited, graph);
24 | }
25 | }
26 | return c;
27 | }
28 |
29 | public static long roadsAndLibraries(int n, int c_lib, int c_road, List> cities) {
30 | List> graph = buildGraph(n, cities);
31 | boolean[] visited = new boolean[n + 1];
32 | List connectedCount = new ArrayList<>();
33 | for(int i = 1; i <= n; i++) {
34 | if(!visited[i]) {
35 | int c = dfs(i, visited, graph);
36 | connectedCount.add(c);
37 | }
38 |
39 | }
40 | System.out.println(connectedCount);
41 | long cost = 0;
42 | // connectedComponentsCount;
43 | for(int cityCount : connectedCount) {
44 | cost += Math.min((c_lib + (cityCount - 1) * c_road), (cityCount * c_lib));
45 | }
46 | return cost;
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/src/graph/RottenOranges.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class Node {
4 | int x, y, t;
5 | public Node(int x, int y, int t) {
6 | this.x = x;
7 | this.y = y;
8 | this.t = t;
9 | }
10 | }
11 |
12 | class Solution {
13 | public int orangesRotting(int[][] grid) {
14 | Queue queue = new LinkedList<>();
15 |
16 | for(int i = 0; i < grid.length; i++) {
17 | for(int j = 0; j < grid[0].length; j++) {
18 | if(grid[i][j] == 2) {
19 | queue.offer(new Node(i, j, 0));
20 | }
21 | }
22 | }
23 |
24 | int ans = 0;
25 |
26 | while(!queue.isEmpty()) {
27 | Node node = queue.poll();
28 | int curr_x = node.x;
29 | int curr_y = node.y;
30 | int curr_time = node.t;
31 |
32 | if((curr_x - 1) >= 0 && grid[curr_x - 1][curr_y] == 1){
33 | grid[curr_x - 1][curr_y] = 2;
34 | queue.offer(new Node(curr_x - 1, curr_y, curr_time + 1));
35 | ans = curr_time + 1;
36 | }
37 | if((curr_x + 1) < grid.length && grid[curr_x + 1][curr_y] == 1) {
38 | grid[curr_x + 1][curr_y] = 2;
39 | queue.offer(new Node(curr_x + 1, curr_y, curr_time + 1));
40 | ans = curr_time + 1;
41 | }
42 | if((curr_y - 1) >= 0 && grid[curr_x][curr_y - 1] == 1){
43 | grid[curr_x][curr_y - 1] = 2;
44 | queue.offer(new Node(curr_x, curr_y - 1, curr_time + 1));
45 | ans = curr_time + 1;
46 | }
47 | if((curr_y + 1) < grid[0].length && grid[curr_x][curr_y + 1] == 1) {
48 | grid[curr_x][curr_y + 1] = 2;
49 | queue.offer(new Node(curr_x, curr_y + 1, curr_time + 1));
50 | ans = curr_time + 1;
51 | }
52 | }
53 |
54 | for(int i = 0; i < grid.length; i++) {
55 | for(int j = 0; j < grid[0].length; j++) {
56 | if(grid[i][j] == 1) {
57 | return -1;
58 | }
59 | }
60 | }
61 |
62 | return ans;
63 | }
64 | }
--------------------------------------------------------------------------------
/src/graph/TopologicalOrdering.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class TopologicalOrdering {
4 |
5 | public static void buildGraphAndIndegree(Map inDegree, Map> graph, int edges[][], int vertices) {
6 | for(int node = 0; node < vertices; node++) {
7 | inDegree.put(node, 0);
8 | graph.put(node, new ArrayList<>());
9 | }
10 | for(int edge[] : edges) {
11 | inDegree.put(edge[1], inDegree.get(edge[1]) + 1);
12 | graph.get(edge[0]).add(edge[1]);
13 | }
14 | }
15 |
16 | public static List topologicalOrdering(int edges[][], int vertices) {
17 | Map inDegree = new HashMap<>();
18 | Map> graph = new HashMap<>();
19 | TopologicalOrdering.buildGraphAndIndegree(inDegree, graph, edges, vertices);
20 | Queue queue = new LinkedList<>();
21 | List ordering = new ArrayList<>();
22 | for(Map.Entry entry : inDegree.entrySet()) {
23 | if(entry.getValue() == 0) {
24 | queue.offer(entry.getKey());
25 | }
26 | }
27 |
28 | while(!queue.isEmpty()) {
29 | int currNode = queue.poll();
30 | ordering.add(currNode);
31 | for(int nbr : graph.get(currNode)) {
32 | inDegree.put(nbr, inDegree.get(nbr) - 1);
33 | if(inDegree.get(nbr) == 0) {
34 | queue.offer(nbr);
35 | }
36 | }
37 | }
38 |
39 | if(ordering.size() == vertices) {
40 | return ordering;
41 | }
42 | return new ArrayList<>();
43 |
44 |
45 | }
46 | public static void main(String[] args) {
47 | int edges[][] = new int[][] {
48 | {0, 4},
49 | {0, 3},
50 | {0, 2},
51 | {1, 0},
52 | {1, 2},
53 | {2, 6},
54 | {3, 5},
55 | {3, 6},
56 | {4, 5}
57 | };
58 | int vertices = 7;
59 | List ordering = TopologicalOrdering.topologicalOrdering(edges, vertices);
60 | for(int order : ordering) {
61 | System.out.print(order + " ");
62 | }
63 | }
64 | }
--------------------------------------------------------------------------------
/src/graph/WaterOptimization.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/graph/WaterOptimization.class
--------------------------------------------------------------------------------
/src/graph/WaterOptimization.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class Pair {
4 | int node, distance;
5 | public Pair(int node, int distance) {
6 | this.node = node;
7 | this.distance = distance;
8 | }
9 | }
10 |
11 | class WaterOptimization {
12 |
13 | private static List> buildGraph(int n, int[][] edges, int[] wells) {
14 | List> graph = new ArrayList<>();
15 | for(int i = 0; i <= n; i++) {
16 | graph.add(new ArrayList<>());
17 | }
18 | for(int[] edge : edges) {
19 | graph.get(edge[0]).add(new Pair(edge[1], edge[2]));
20 | graph.get(edge[1]).add(new Pair(edge[0], edge[2]));
21 | }
22 | for(int i = 1; i <= n; i++) {
23 | graph.get(0).add(new Pair(i, wells[i - 1]));
24 | graph.get(i).add(new Pair(0, wells[i - 1]));
25 | }
26 | return graph;
27 | }
28 |
29 | private static int findMinCost(int n, int[][] edges, int[] wells) {
30 | List> graph = WaterOptimization.buildGraph(n, edges, wells);
31 | PriorityQueue minHeap = new PriorityQueue<>((p1, p2) -> (p1.distance - p2.distance));
32 |
33 | boolean[] mstSet = new boolean[n + 1];
34 | int[] distance = new int[n + 1];
35 | Arrays.fill(distance, Integer.MAX_VALUE);
36 | int[] parent = new int[n + 1];
37 |
38 | distance[1] = 0;
39 | parent[1] = -1;
40 | minHeap.offer(new Pair(1, distance[1]));
41 |
42 | while(!minHeap.isEmpty()) {
43 | Pair pair = minHeap.poll();
44 | int currNode = pair.node;
45 |
46 | if(mstSet[currNode]) continue;
47 |
48 | mstSet[currNode] = true;
49 |
50 | for(Pair nbrPair : graph.get(currNode)) {
51 | int nbrNode = nbrPair.node;
52 | int nbrDistance = nbrPair.distance;
53 |
54 | if(!mstSet[nbrNode] && nbrDistance < distance[nbrNode]) {
55 | distance[nbrNode] = nbrDistance;
56 | parent[nbrNode] = currNode;
57 | minHeap.offer(nbrPair);
58 | }
59 | }
60 | }
61 | int minCost = 0;
62 | for(int i = 0; i <= n; i++) {
63 | minCost += distance[i];
64 | }
65 | return minCost ;
66 | }
67 |
68 | public static void main(String[] args) {
69 | int[][] edges = new int[][]{{1, 2, 3}, {1, 4, 6}, {1, 5, 2}, {2, 4, 5}, {3, 5, 7}};
70 | int[] wells = new int[]{1, 4, 6, 5, 3};
71 | int nodes = 5;
72 | int cost = WaterOptimization.findMinCost(nodes, edges, wells);
73 | System.out.println(cost);
74 | }
75 | }
--------------------------------------------------------------------------------
/src/linkedlist/DesignLinkedList.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/linkedlist/DesignLinkedList.class
--------------------------------------------------------------------------------
/src/linkedlist/DesignLinkedList.java:
--------------------------------------------------------------------------------
1 | class Node {
2 | int data;
3 | Node next;
4 | public Node(int data) {
5 | this.data = data;
6 | this.next = null;
7 | }
8 | }
9 |
10 | class DesignLinkedList {
11 |
12 | Node head, tail;
13 |
14 | public DesignLinkedList() {
15 | this.head = null;
16 | this.tail = null;
17 | }
18 |
19 | public void insertAtBeginning(int data) {
20 | Node node = new Node(data);
21 | if(this.head == null) {
22 | this.head = node;
23 | this.tail = node;
24 | } else {
25 | node.next = this.head;
26 | this.head = node;
27 | }
28 |
29 | }
30 |
31 | // O(N) to insert a node at the end.
32 | public void insertAtEnd_N(int data) {
33 | Node node = new Node(data);
34 | if(this.head == null) {
35 | this.head = node;
36 | } else {
37 | Node temp = this.head;
38 | while(temp.next != null) {
39 | temp = temp.next;
40 | }
41 | temp.next = node;
42 | }
43 |
44 | }
45 |
46 | // (1) to insert a node at the end.
47 | public void insertAtEnd(int data) {
48 | Node node = new Node(data);
49 | if(this.head == null) {
50 | this.head = node;
51 | this.tail = node;
52 | } else {
53 | this.tail.next = node;
54 | this.tail = node;
55 | }
56 | }
57 |
58 | public int deleteNode(int data) {
59 | if(this.head == null)
60 | return -1;
61 | Node temp = this.head;
62 | if(temp.data == data) {
63 | this.head = temp.next;
64 | return data;
65 | }
66 | Node prev = temp;
67 | temp = temp.next;
68 | while(temp != null) {
69 | if(temp.data == data) {
70 | prev.next = temp.next;
71 | if(temp.next == null) {
72 | this.tail = prev;
73 | }
74 | return data;
75 | }
76 | prev = temp;
77 | temp = temp.next;
78 | }
79 | return -1;
80 | }
81 |
82 | public void printList() {
83 | Node temp = this.head;
84 | while(temp != null) {
85 | System.out.print(temp.data + " -> ");
86 | temp = temp.next;
87 | }
88 | System.out.println("null");
89 | }
90 |
91 | public static void main(String[] args) {
92 | DesignLinkedList ll = new DesignLinkedList();
93 | ll.insertAtEnd(30);
94 | ll.insertAtEnd(40);
95 | ll.insertAtEnd(50);
96 | ll.insertAtBeginning(20);
97 | ll.insertAtBeginning(10);
98 | ll.insertAtEnd(60);
99 | ll.printList();
100 | ll.deleteNode(20);
101 | ll.printList();
102 | ll.deleteNode(60);
103 | ll.printList();
104 | ll.insertAtEnd(70);
105 | ll.printList();
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/src/linkedlist/LFUCache.java:
--------------------------------------------------------------------------------
1 | class Node {
2 | int key, value, frequency;
3 | Node next, prev;
4 | public Node(int key, int value, int frequency) {
5 | this.key = key;
6 | this.value = value;
7 | this.frequency = frequency;
8 | }
9 | }
10 |
11 | class DoublyLinkedList {
12 | int size;
13 | Node head, tail;
14 |
15 | public DoublyLinkedList() {
16 | this.size = 0;
17 | this.head = new Node(-1, -1, -1);
18 | this.tail = new Node(-1, -1, -1);
19 | this.head.next = this.tail;
20 | this.tail.prev = this.head;
21 | }
22 |
23 | public void addNode(Node node) {
24 | node.next = this.head.next;
25 | this.head.next = node;
26 | node.prev = this.head;
27 | node.next.prev = node;
28 | this.size += 1;
29 | }
30 |
31 | public void deleteNode(Node node) {
32 | node.prev.next = node.next;
33 | node.next.prev = node.prev;
34 | this.size -= 1;
35 | }
36 | }
37 |
38 | class LFUCache {
39 |
40 | int minimumFrequency, capacity;
41 | Map cacheMap;
42 | Map lfuMap;
43 |
44 | public LFUCache(int capacity) {
45 | this.capacity = capacity;
46 | this.minimumFrequency = 0;
47 | cacheMap = new HashMap<>();
48 | lfuMap = new HashMap<>();
49 | }
50 |
51 | public void updateNode(Node node) {
52 | int currentFrequency = node.frequency;
53 | DoublyLinkedList lruCache = lfuMap.get(currentFrequency);
54 | lruCache.deleteNode(node);
55 |
56 | node.frequency += 1;
57 |
58 | if(this.minimumFrequency == currentFrequency && lruCache.size == 0) {
59 | this.minimumFrequency += 1;
60 | }
61 |
62 | if(!lfuMap.containsKey(node.frequency)) {
63 | lfuMap.put(node.frequency, new DoublyLinkedList());
64 | }
65 | lruCache = lfuMap.get(node.frequency);
66 | lruCache.addNode(node);
67 | }
68 |
69 | public int get(int key) {
70 | if(cacheMap.containsKey(key)) {
71 | Node node = cacheMap.get(key);
72 | int value = node.value;
73 | updateNode(node);
74 | return node.value;
75 | } else {
76 | return -1;
77 | }
78 | }
79 |
80 | public void put(int key, int value) {
81 |
82 | if(this.capacity == 0) return;
83 |
84 | if(cacheMap.containsKey(key)) {
85 | Node node = cacheMap.get(key);
86 | node.value = value;
87 | updateNode(node);
88 | } else {
89 | if(this.capacity == cacheMap.size()) {
90 | DoublyLinkedList lruCache = lfuMap.get(this.minimumFrequency);
91 | Node node = lruCache.tail.prev;
92 | cacheMap.remove(node.key);
93 | lruCache.deleteNode(node);
94 | }
95 | this.minimumFrequency = 1;
96 | Node node = new Node(key, value, this.minimumFrequency);
97 | cacheMap.put(key, node);
98 | if(!lfuMap.containsKey(this.minimumFrequency)) {
99 | lfuMap.put(this.minimumFrequency, new DoublyLinkedList());
100 | }
101 | DoublyLinkedList lruCache = lfuMap.get(this.minimumFrequency);
102 | lruCache.addNode(node);
103 | }
104 | }
105 | }
106 |
107 | /**
108 | * Your LFUCache object will be instantiated and called as such:
109 | * LFUCache obj = new LFUCache(capacity);
110 | * int param_1 = obj.get(key);
111 | * obj.put(key,value);
112 | */
--------------------------------------------------------------------------------
/src/linkedlist/Node.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/linkedlist/Node.class
--------------------------------------------------------------------------------
/src/maths/SplitArrayGCD.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/maths/SplitArrayGCD.class
--------------------------------------------------------------------------------
/src/maths/SplitArrayGCD.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | /*
3 | 19, 28, 14, 20, 1, 3, 9, 5, 3
4 | */
5 | class SplitArrayGCD {
6 |
7 | public static int gcd(int a, int b) {
8 | if(b != 0) {
9 | return gcd(b, a % b);
10 | } else {
11 | return a;
12 | }
13 | }
14 |
15 | public static int splitArray(int arr[]) {
16 | int ans[] = new int[arr.length + 1];
17 | for(int i = arr.length - 1; i >= 0; i--) {
18 | ans[i] = ans[i + 1] + 1;
19 | for(int j = i + 1; j < arr.length; j++) {
20 | if(SplitArrayGCD.gcd(arr[i], arr[j]) > 1) {
21 | ans[i] = Math.min(ans[i], ans[j + 1] + 1);
22 | }
23 | }
24 | }
25 | return ans[0];
26 | }
27 |
28 | public static void main(String[] args) {
29 | int arr[] = new int[]{2, 3, 4, 5, 7, 11, 9};
30 | int ans = SplitArrayGCD.splitArray(arr);
31 | System.out.println(ans);
32 | }
33 | }
--------------------------------------------------------------------------------
/src/priorityqueue/FrequencySort.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | import java.io.*;
3 |
4 | class FrequencySort {
5 |
6 | public static String sortCharacters(String s) {
7 | Map hashMap = new HashMap<>();
8 | for(char ch : s.toCharArray()) {
9 | hashMap.put(ch, hashMap.getOrDefault(ch, 0) + 1);
10 | }
11 | PriorityQueue> maxHeap =
12 | new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
13 | for(Map.Entry entry : hashMap.entrySet()) {
14 | maxHeap.offer(entry);
15 | }
16 |
17 | StringBuilder ans = new StringBuilder();
18 | while(!maxHeap.isEmpty()) {
19 | Map.Entry entry = maxHeap.poll();
20 | for(int i = 0; i < entry.getValue(); i++) {
21 | ans.append(entry.getKey());
22 | }
23 | }
24 | return ans.toString();
25 | }
26 | public static void main(String[] args) {
27 | String s = "apaprsqpp";
28 | String ans = FrequencySort.sortCharacters(s);
29 | System.out.println(ans);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/priorityqueue/KClosestPointsToOrigin.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class Point {
4 | int x, y, d;
5 | public Point(int x, int y, int d) {
6 | this.x = x;
7 | this.y = y;
8 | this.d = d;
9 | }
10 | }
11 |
12 | class KClosestPointsToOrigin {
13 |
14 | public static int[][] kClosestPoints(int points[][], int k) {
15 | PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> b.d - a.d);
16 | for(int i = 0; i < points.length; i++) {
17 | int x = points[i][0];
18 | int y = points[i][1];
19 | int distance = x * x + y * y;
20 | maxHeap.offer(new Point(x, y, distance));
21 | if(maxHeap.size() == k + 1) {
22 | maxHeap.poll();
23 | }
24 | }
25 | int ans[][] = new int[k][2];
26 | for(int i = 0; i < k; i++) {
27 | Point point = maxHeap.poll();
28 | ans[i][0] = point.x;
29 | ans[i][1] = point.y;
30 | }
31 | return ans;
32 | }
33 |
34 | public static void main(String[] args) {
35 | int points[][] = new int[][] {{-4, 3}, {-1, 1}, {5, 5}, {3, 1}, {-4, -3}, {2, -2}};
36 | int k = 3;
37 | int ans[][] = KClosestPointsToOrigin.kClosestPoints(points, k);
38 | for(int point[] : ans) {
39 | System.out.print(point[0] + " " + point[1]);
40 | System.out.println();
41 | }
42 | }
43 | }
--------------------------------------------------------------------------------
/src/priorityqueue/LargestKElements.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/priorityqueue/LargestKElements.class
--------------------------------------------------------------------------------
/src/priorityqueue/LargestKElements.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class LargestKElements {
4 |
5 | public static int[] largestKElements(int arr[], int k) {
6 | PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a - b);
7 | for(int i = 0; i < arr.length; i++) {
8 | minHeap.offer(arr[i]);
9 | if(minHeap.size() == k + 1) {
10 | minHeap.poll();
11 | }
12 | }
13 | int ans[] = new int[k];
14 | for(int i = 0; i < k; i++) {
15 | ans[i] = minHeap.poll();
16 | }
17 | return ans;
18 | }
19 |
20 | public static void main(String[] args) {
21 | int arr[] = {1, 4, 5, 3, 7, 8, 6, 10};
22 | int k = 3;
23 | int ans[] = LargestKElements.largestKElements(arr, k);
24 | for(int a : ans) {
25 | System.out.print(a + " ");
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/src/priorityqueue/MeetingRoomsII.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/priorityqueue/MeetingRoomsII.class
--------------------------------------------------------------------------------
/src/priorityqueue/MeetingRoomsII.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class MeetingRoomsII {
4 |
5 | public static int minimumRooms(int meetings[][]) {
6 |
7 | Arrays.sort(meetings, (a, b) -> Integer.compare(a[0], b[0]));
8 | PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a - b);
9 |
10 | for(int meeting[] : meetings) {
11 | if(!minHeap.isEmpty() && meeting[0] >= minHeap.peek()) {
12 | minHeap.poll();
13 | }
14 | minHeap.offer(meeting[1]);
15 | }
16 | return minHeap.size();
17 |
18 | }
19 | public static void main(String[] args) {
20 | int meetings[][] =
21 | new int[][] {{1, 4}, {2, 3}, {2, 3}, {3, 5}, {1, 4}, {6, 8}, {4, 7}, {7, 9}};
22 | int rooms = MeetingRoomsII.minimumRooms(meetings);
23 | System.out.println(rooms);
24 |
25 | }
26 | }
--------------------------------------------------------------------------------
/src/priorityqueue/ReorganizeString.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | import java.io.*;
3 |
4 | class ReorganizeString {
5 |
6 | public static String reorganizeString(String s) {
7 |
8 | Map hashMap = new HashMap<>();
9 | for(char ch : s.toCharArray()) {
10 | hashMap.put(ch, hashMap.getOrDefault(ch, 0) + 1);
11 | }
12 |
13 | PriorityQueue> maxHeap =
14 | new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
15 | for(Map.Entry entry : hashMap.entrySet()) {
16 | maxHeap.offer(entry);
17 | }
18 |
19 | StringBuilder res = new StringBuilder();
20 | while(maxHeap.size() >= 2) {
21 | Map.Entry entry1 = maxHeap.poll();
22 | Map.Entry entry2 = maxHeap.poll();
23 | res.append(entry1.getKey());
24 | res.append(entry2.getKey());
25 | entry1.setValue(entry1.getValue() - 1);
26 | entry2.setValue(entry2.getValue() - 1);
27 | if(entry1.getValue() > 0) {
28 | maxHeap.offer(entry1);
29 | }
30 | if(entry2.getValue() > 0) {
31 | maxHeap.offer(entry2);
32 | }
33 | }
34 |
35 | if(maxHeap.isEmpty()) {
36 | return res.toString();
37 | } else {
38 | Map.Entry entry = maxHeap.poll();
39 | if(entry.getValue() == 1) {
40 | res.append(entry.getKey());
41 | return res.toString();
42 | } else {
43 | return "";
44 | }
45 | }
46 | }
47 | public static void main(String[] args) {
48 | String s = "aaabcdddaa";
49 | String ans = ReorganizeString.reorganizeString(s);
50 | System.out.println(ans);
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/priorityqueue/ReorganizeStringKDistanceApart.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/priorityqueue/ReorganizeStringKDistanceApart.class
--------------------------------------------------------------------------------
/src/priorityqueue/ReorganizeStringKDistanceApart.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class ReorganizeStringKDistanceApart {
4 |
5 | public static String reorganizeString(String s, int k) {
6 |
7 | Map hashMap = new HashMap<>();
8 | for(char ch : s.toCharArray()) {
9 | hashMap.put(ch, hashMap.getOrDefault(ch, 0) + 1);
10 | }
11 |
12 | PriorityQueue> maxHeap =
13 | new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
14 | for(Map.Entry entry : hashMap.entrySet()) {
15 | maxHeap.offer(entry);
16 | }
17 |
18 | StringBuilder result = new StringBuilder();
19 |
20 | Queue> queue = new LinkedList<>();
21 |
22 | while(!maxHeap.isEmpty()) {
23 | Map.Entry entry = maxHeap.poll();
24 | result.append(entry.getKey());
25 | entry.setValue(entry.getValue() - 1);
26 | queue.offer(entry);
27 | if(queue.size() == k) {
28 | Map.Entry queueFront = queue.poll();
29 | if(queueFront.getValue() > 0) {
30 | maxHeap.offer(queueFront);
31 | }
32 | }
33 | }
34 |
35 | if(result.length() == s.length()) {
36 | return result.toString();
37 | } else {
38 | return "";
39 | }
40 |
41 | }
42 |
43 | public static void main(String[] args) {
44 | String s = "aabbcc";
45 | int k = 3;
46 | String ans = reorganizeString(s, k);
47 | System.out.println(ans);
48 | }
49 | }
--------------------------------------------------------------------------------
/src/priorityqueue/SmallestKElements.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class SmallestKElements {
4 |
5 | public static int[] smallestKElements(int arr[], int k) {
6 | PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> b - a);
7 | for(int i = 0; i < arr.length; i++) {
8 | maxHeap.offer(arr[i]);
9 | if(maxHeap.size() == k + 1) {
10 | maxHeap.poll();
11 | }
12 | }
13 | int ans[] = new int[k];
14 | for(int i = 0; i < k; i++) {
15 | ans[i] = maxHeap.poll();
16 | }
17 | return ans;
18 | }
19 |
20 | public static void main(String[] args) {
21 | int arr[] = {1, 4, 5, 3, 7, 8, 6, 10};
22 | int k = 3;
23 | int ans[] = SmallestKElements.smallestKElements(arr, k);
24 | for(int a : ans) {
25 | System.out.print(a + " ");
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/src/recursion/ClimbingStairs.java:
--------------------------------------------------------------------------------
1 | public class ClimbingStairs {
2 |
3 | public static int solve(int currStair, int n) {
4 | if(currStair == n) return 1;
5 | if(currStair > n) return 0;
6 |
7 | int leftCount = solve(currStair + 1, n);
8 | int rightCount = solve(currStair + 2, n);
9 |
10 | return leftCount + rightCount;
11 | }
12 |
13 | public static int findWays(int n) {
14 | return ClimbingStairs.solve(0, n);
15 | }
16 |
17 | public static void main(String[] args) {
18 | int n = 4;
19 | System.out.println(ClimbingStairs.findWays(n));
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/recursion/DishDistribution.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/recursion/DishDistribution.class
--------------------------------------------------------------------------------
/src/recursion/DishDistribution.java:
--------------------------------------------------------------------------------
1 | public class DishDistribution {
2 |
3 | private static int solve(int dishes, int i, int[][] cooks) {
4 | if(i == cooks.length && dishes == 0) return 1;
5 | if(i == cooks.length || dishes < 0) return 0;
6 | int count = 0;
7 | int min = cooks[i][0];
8 | int max = cooks[i][1];
9 | if(dishes < min) return 0;
10 |
11 | for(int j = min; j <= max; j++) {
12 | count += solve(dishes - j, i + 1, cooks);
13 | }
14 | return count;
15 | }
16 |
17 | private static int distribute(int dishes, int cno, int[][] cooks) {
18 | return DishDistribution.solve(dishes, 0, cooks);
19 | }
20 |
21 | public static void main(String[] args) {
22 | int dishes = 3;
23 | int cno = 2;
24 | int[][] cooks = new int[][]{{0, 3}, {1, 3}};
25 | System.out.println(DishDistribution.distribute(dishes, cno, cooks));
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/recursion/MaximumPriceProblem.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/recursion/MaximumPriceProblem.class
--------------------------------------------------------------------------------
/src/recursion/MaximumPriceProblem.java:
--------------------------------------------------------------------------------
1 | public class MaximumPriceProblem {
2 |
3 | public static int solve(int[] winePrice, int left, int right) {
4 | if(left > right) return 0;
5 | int year = winePrice.length - (right - left);
6 | int leftCost = winePrice[left] * year + solve(winePrice, left + 1, right);
7 | int rightCost = winePrice[right] * year + solve(winePrice, left, right - 1);
8 | return Math.max(leftCost, rightCost);
9 | }
10 |
11 | public static int maxPrice(int[] winePrice) {
12 | return MaximumPriceProblem.solve(winePrice, 0, winePrice.length - 1);
13 | }
14 | public static void main(String[] args) {
15 | int[] winePrice = new int[]{2, 3, 5, 1, 4};
16 | System.out.println(MaximumPriceProblem.maxPrice(winePrice));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/recursion/MinCostClimbingStairs.java:
--------------------------------------------------------------------------------
1 | public class MinCostClimbingStairs {
2 |
3 | public static int solve(int n, int[] cost) {
4 |
5 | if(n <= 1) return 0;
6 |
7 | int oneStep = cost[n - 1] + solve(n - 1, cost);
8 | int twoStep = cost[n - 2] + solve(n - 2, cost);
9 | return Math.min(oneStep, twoStep);
10 | }
11 |
12 | public static int minCost(int[] cost) {
13 | return MinCostClimbingStairs.solve(cost.length, cost);
14 | }
15 |
16 | public static void main(String[] args) {
17 | int cost[] = new int[]{10, 15, 20};
18 | System.out.println(MinCostClimbingStairs.minCost(cost));
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/recursion/StoneGame.java:
--------------------------------------------------------------------------------
1 | class StoneGame {
2 |
3 | public static int solve(int stones[], int left, int right) {
4 |
5 | if(left > right) {
6 | return 0;
7 | }
8 |
9 | int left_ans = stones[left] - solve(stones, left + 1, right);
10 | int right_ans = stones[right] - solve(stones, left, right - 1);
11 | return Math.max(left_ans, right_ans);
12 |
13 | }
14 |
15 | public static boolean stoneGame(int stones[]) {
16 | int val = StoneGame.solve(stones, 0, stones.length - 1);
17 | if(val > 0) return true;
18 | else return false;
19 | }
20 | public static void main(String[] args) {
21 | int stones[] = new int[]{3, 2, 7, 3};
22 | System.out.println(StoneGame.stoneGame(stones));
23 | }
24 | }
--------------------------------------------------------------------------------
/src/recursion/StoneGame3.java:
--------------------------------------------------------------------------------
1 | class StoneGame3 {
2 |
3 | public static int solve(int stones[], int i) {
4 |
5 | if(i >= stones.length) {
6 | return 0;
7 | }
8 |
9 | int a, b, c;
10 | b = Integer.MIN_VALUE;
11 | c = Integer.MIN_VALUE;
12 | a = stones[i] - solve(stones, i + 1);
13 | if(i + 1 < stones.length) {
14 | b = stones[i] + stones[i + 1] - solve(stones, i + 2);
15 | }
16 | if(i + 1 < stones.length && i + 2 < stones.length) {
17 | c = stones[i] + stones[i + 1] + stones[i + 2] - solve(stones, i + 3);
18 | }
19 |
20 | return Math.max(a, Math.max(b, c));
21 | }
22 |
23 | public static String stoneGame(int stones[]) {
24 | int val = StoneGame3.solve(stones, 0);
25 | if(val > 0) return "Alice";
26 | else if(val == 0) return "Tie";
27 | else return "Bob";
28 | }
29 | public static void main(String[] args) {
30 | int stones[] = new int[]{5, 2, 4, 7};
31 | System.out.println(StoneGame3.stoneGame(stones));
32 | }
33 | }
--------------------------------------------------------------------------------
/src/recursion/StoneGameRaw.java:
--------------------------------------------------------------------------------
1 | class StoneGameRaw {
2 |
3 | public static int solve(int stones[], int left, int right, boolean alice) {
4 |
5 | if(left > right) {
6 | return 0;
7 | }
8 |
9 | if(alice) {
10 | int left_ans = stones[left] + solve(stones, left + 1, right, !alice);
11 | int right_ans = stones[right] + solve(stones, left, right - 1, !alice);
12 | return Math.max(left_ans, right_ans);
13 | } else {
14 | int left_ans = -stones[left] + solve(stones, left + 1, right, !alice);
15 | int right_ans = -stones[right] + solve(stones, left, right - 1, !alice);
16 | return Math.min(left_ans, right_ans);
17 | }
18 |
19 | }
20 |
21 | public static boolean stoneGame(int stones[]) {
22 | int val = StoneGameRaw.solve(stones, 0, stones.length - 1, true);
23 | if(val > 0) return true;
24 | else return false;
25 | }
26 | public static void main(String[] args) {
27 | int stones[] = new int[]{3, 2, 7, 3};
28 | System.out.println(StoneGameRaw.stoneGame(stones));
29 | }
30 | }
--------------------------------------------------------------------------------
/src/slidingwindow/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/slidingwindow/.DS_Store
--------------------------------------------------------------------------------
/src/slidingwindow/AllAnagrams.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class AllAnagrams {
4 | public List findAnagrams(String s, String p) {
5 | List result = new ArrayList<>();
6 | Map map = new HashMap<>();
7 | for(char ch : p.toCharArray()) {
8 | map.put(ch, map.getOrDefault(ch, 0) + 1);
9 | }
10 |
11 | int windowStart = 0;
12 | int matched = 0;
13 |
14 | for(int windowEnd = 0; windowEnd < s.length(); windowEnd++) {
15 |
16 | char currChar = s.charAt(windowEnd);
17 | if(map.containsKey(currChar)) {
18 | map.put(currChar, map.get(currChar) - 1);
19 | if(map.get(currChar) == 0) {
20 | matched += 1;
21 | }
22 | }
23 |
24 | if(matched == map.size()) {
25 | result.add(windowStart);
26 | }
27 |
28 | if(windowEnd >= p.length() - 1) {
29 | char leftChar = s.charAt(windowStart);
30 | windowStart += 1;
31 | if(map.containsKey(leftChar)) {
32 | if(map.get(leftChar) == 0) {
33 | matched -= 1;
34 | }
35 | map.put(leftChar, map.get(leftChar) + 1);
36 | }
37 | }
38 | }
39 | return result;
40 | }
41 | }
--------------------------------------------------------------------------------
/src/slidingwindow/AverageSubarrayOfSizeK.java:
--------------------------------------------------------------------------------
1 | package slidingwindow;
2 |
3 | public class AverageSubarrayOfSizeK {
4 |
5 | public static double[] averageSubarray(int arr[], int k) {
6 | double ans[] = new double[arr.length - k + 1];
7 | int windowStart = 0;
8 | int windowSum = 0;
9 | for(int windowEnd = 0; windowEnd < arr.length; windowEnd++) {
10 | windowSum += arr[windowEnd];
11 | if(windowEnd >= k - 1) {
12 | ans[windowStart] = (double) windowSum/k;
13 | windowSum -= arr[windowStart];
14 | windowStart += 1;
15 | }
16 | }
17 | return ans;
18 | }
19 |
20 | public static void main(String[] args) {
21 | int arr[] = new int[]{1, 2, 3, 4, 5, 6};
22 | int k = 3;
23 | double ans[] = AverageSubarrayOfSizeK.averageSubarray(arr, k);
24 | for(double a : ans) {
25 | System.out.print(a + " ");
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/slidingwindow/KDistinctCharacters.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/slidingwindow/KDistinctCharacters.class
--------------------------------------------------------------------------------
/src/slidingwindow/KDistinctCharacters.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class KDistinctCharacters {
4 |
5 | public static int maxLength(String s, int k) {
6 | int windowStart = 0;
7 | int ansStart = 0;
8 | int ansEnd = 0;
9 | int maxLength = Integer.MIN_VALUE;
10 | Map map = new HashMap<>();
11 |
12 | for(int windowEnd = 0; windowEnd < s.length(); windowEnd++) {
13 | char currChar = s.charAt(windowEnd);
14 | map.put(currChar, map.getOrDefault(currChar, 0) + 1);
15 | while(map.size() > k) {
16 | char leftChar = s.charAt(windowStart);
17 | map.put(leftChar, map.get(leftChar) - 1);
18 | if(map.get(leftChar) == 0) {
19 | map.remove(leftChar);
20 | }
21 | windowStart += 1;
22 | }
23 | // maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
24 | if(windowEnd - windowStart + 1 > maxLength) {
25 | maxLength = windowEnd - windowStart + 1;
26 | ansStart = windowStart;
27 | ansEnd = windowEnd;
28 | }
29 | }
30 | System.out.println(s.substring(ansStart, ansEnd + 1));
31 | return maxLength;
32 | }
33 | public static void main(String[] args) {
34 | String s = "aaabccccbcd";
35 | System.out.println(KDistinctCharacters.maxLength(s, 2));
36 | }
37 | }
--------------------------------------------------------------------------------
/src/slidingwindow/LongestSubstringAfterReplacement.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/slidingwindow/LongestSubstringAfterReplacement.class
--------------------------------------------------------------------------------
/src/slidingwindow/LongestSubstringAfterReplacement.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class LongestSubstringAfterReplacement {
4 |
5 | public static int maxLength(String s, int k) {
6 | int windowStart = 0;
7 | int maxLength = Integer.MIN_VALUE;
8 | int maximumFrequency = 0;
9 | Map map = new HashMap<>();
10 |
11 | for(int windowEnd = 0; windowEnd < s.length(); windowEnd++) {
12 | char currChar = s.charAt(windowEnd);
13 | map.put(currChar, map.getOrDefault(currChar, 0) + 1);
14 | maximumFrequency = Math.max(maximumFrequency, map.get(currChar));
15 | if((windowEnd - windowStart + 1) - maximumFrequency > k) {
16 | char leftChar = s.charAt(windowStart);
17 | map.put(leftChar, map.get(leftChar) - 1);
18 | windowStart += 1;
19 | }
20 | maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
21 | }
22 | return maxLength;
23 | }
24 | public static void main(String[] args) {
25 | String s = "ababbab";
26 | System.out.println(LongestSubstringAfterReplacement.maxLength(s, 2));
27 | }
28 | }
--------------------------------------------------------------------------------
/src/slidingwindow/MaxSubarraySum.java:
--------------------------------------------------------------------------------
1 | package slidingwindow;
2 |
3 | public class MaxSubarraySum {
4 |
5 | public static int maxSubarraySum(int arr[], int k) {
6 | int windowStart = 0;
7 | int windowSum = 0;
8 | int maxSum = Integer.MIN_VALUE;
9 | for(int windowEnd = 0; windowEnd < arr.length; windowEnd++) {
10 | windowSum += arr[windowEnd];
11 | if(windowEnd >= k - 1) {
12 | maxSum = Math.max(maxSum, windowSum);
13 | windowSum -= arr[windowStart];
14 | windowStart += 1;
15 | }
16 | }
17 | return maxSum;
18 | }
19 |
20 | public static void main(String[] args) {
21 | int arr[] = new int[]{1, 2, 3, 4, 5, 6};
22 | int k = 3;
23 |
24 | int maxSum = MaxSubarraySum.maxSubarraySum(arr, k);
25 | System.out.println(maxSum);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/slidingwindow/NoRepeatSubstring.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class NoRepeatSubString {
4 |
5 | public static int findLength(String s) {
6 | int windowStart = 0, maxLength = 0;
7 | Map map = new HashMap<>();
8 |
9 | for(int windowEnd = 0; windowEnd < s.length(); windowEnd++) {
10 | char rightChar = s.charAt(windowEnd);
11 | if(map.containsKey(rightChar)) {
12 | windowStart = Math.max(windowStart, map.get(rightChar) + 1);
13 | }
14 | map.put(rightChar, windowEnd);
15 | maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
16 | }
17 | return maxLength;
18 | }
19 |
20 | public static void main(String[] args) {
21 | String s = "aabccbb";
22 | int length = findLength(s);
23 | System.out.println(length);
24 | }
25 | }
--------------------------------------------------------------------------------
/src/slidingwindow/PermutationInString.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/slidingwindow/PermutationInString.class
--------------------------------------------------------------------------------
/src/slidingwindow/PermutationInString.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class PermutationInString {
4 | public static boolean isFound(String s, String p) {
5 | Map map = new HashMap<>();
6 | for(char ch : p.toCharArray()) {
7 | map.put(ch, map.getOrDefault(ch, 0) + 1);
8 | }
9 |
10 | int windowStart = 0;
11 | int matched = 0;
12 |
13 | for(int windowEnd = 0; windowEnd < s.length(); windowEnd++) {
14 | char currChar = s.charAt(windowEnd);
15 | if(map.containsKey(currChar)) {
16 | map.put(currChar, map.get(currChar) - 1);
17 | if(map.get(currChar) == 0) {
18 | matched += 1;
19 | }
20 | }
21 |
22 | if(matched == map.size()) {
23 | return true;
24 | }
25 |
26 | if(windowEnd >= p.length() - 1) {
27 | char leftChar = s.charAt(windowStart);
28 | windowStart += 1;
29 | if(map.containsKey(leftChar)) {
30 | if(map.get(leftChar) == 0) {
31 | matched -= 1;
32 | }
33 | map.put(leftChar, map.get(leftChar) + 1);
34 | }
35 | }
36 |
37 | }
38 | return false;
39 | }
40 | }
--------------------------------------------------------------------------------
/src/slidingwindow/SubarrayWithKDistinctCharacters.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | import java.io.*;
3 |
4 | class SubarrayWithKDistinctCharacters {
5 |
6 | public static int maxSubarrayWithKDistinctCharacters(String s, int k) {
7 | int windowStart = 0;
8 | int maxLength = Integer.MIN_VALUE;
9 | Map map = new HashMap<>();
10 | for(int windowEnd = 0; windowEnd < s.length(); windowEnd++) {
11 | char currChar = s.charAt(windowEnd);
12 | map.put(currChar, map.getOrDefault(currChar, 0) + 1);
13 |
14 | // invalid window case, we need to shrink the window until the window becomes valid
15 | while(map.size() > k) {
16 | char leftChar = s.charAt(windowStart);
17 | windowStart += 1;
18 | map.put(leftChar, map.get(leftChar) - 1);
19 | if(map.get(leftChar) == 0) {
20 | map.remove(leftChar);
21 | }
22 | }
23 | maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
24 | }
25 | return maxLength;
26 | }
27 |
28 | public static void main(String[] args) {
29 | String s = "abacdcdcdabcd";
30 | int k = 3;
31 | System.out.println(SubarrayWithKDistinctCharacters.maxSubarrayWithKDistinctCharacters(s, k));
32 | }
33 | }
--------------------------------------------------------------------------------
/src/stack/InfixToPostfix.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/stack/InfixToPostfix.class
--------------------------------------------------------------------------------
/src/stack/InfixToPostfix.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class InfixToPostfix {
4 | public static int precedence(char ch) {
5 | if(ch == '+' || ch == '-') return 1;
6 | else if(ch == '*' || ch == '/') return 2;
7 | else if(ch == '^') return 3;
8 | else return -1;
9 | }
10 | public static String infixToPostfix(String s) {
11 | Stack stack = new Stack<>();
12 | StringBuilder result = new StringBuilder();
13 | for(int i = 0; i < s.length(); i++) {
14 | char ch = s.charAt(i);
15 | if(Character.isLetterOrDigit(ch)) {
16 | result.append(ch);
17 | } else if(ch == '(') {
18 | stack.push(ch);
19 | } else if(ch == ')') {
20 | while(!stack.isEmpty() && stack.peek() != '(') {
21 | result.append(stack.pop());
22 | }
23 | if(stack.isEmpty()) return "NA";
24 | stack.pop();
25 | } else {
26 | while(!stack.isEmpty() && InfixToPostfix.precedence(ch) <= InfixToPostfix.precedence(stack.peek())) {
27 | result.append(stack.pop());
28 | }
29 | stack.push(ch);
30 | }
31 | }
32 | while(!stack.isEmpty()) {
33 | if(stack.peek() == '(') return "NA";
34 | result.append(stack.pop());
35 | }
36 | return result.toString();
37 | }
38 | public static void main(String[] args) {
39 | // String s = "a+b*(c^d-e)^(f+g*h)-i";
40 | String s = "a+b*c)";
41 | String ans = InfixToPostfix.infixToPostfix(s);
42 | System.out.println(ans);
43 | }
44 | }
--------------------------------------------------------------------------------
/src/stack/MaximumAreaHistogram.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/stack/MaximumAreaHistogram.class
--------------------------------------------------------------------------------
/src/stack/MaximumAreaHistogram.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class MaximumAreaHistogram {
4 |
5 | public static int[] nsel(int arr[]) {
6 | Stack stack = new Stack<>();
7 | int nsel[] = new int[arr.length];
8 | for(int i = 0; i < arr.length; i++) {
9 | while(!stack.isEmpty() && arr[stack.peek()] >= arr[i]) {
10 | stack.pop();
11 | }
12 | if(stack.isEmpty()) {
13 | nsel[i] = -1;
14 | } else {
15 | nsel[i] = stack.peek();
16 | }
17 | stack.push(i);
18 | }
19 | return nsel;
20 | }
21 |
22 | public static int[] nser(int arr[]) {
23 | Stack stack = new Stack<>();
24 | int nser[] = new int[arr.length];
25 | for(int i = arr.length - 1; i >= 0; i--) {
26 | while(!stack.isEmpty() && arr[stack.peek()] >= arr[i]) {
27 | stack.pop();
28 | }
29 | if(stack.isEmpty()) {
30 | nser[i] = arr.length;
31 | } else {
32 | nser[i] = stack.peek();
33 | }
34 | stack.push(i);
35 | }
36 | return nser;
37 | }
38 |
39 | public static int maximumAreaHistogram(int arr[]) {
40 | int nser_i[] = MaximumAreaHistogram.nser(arr);
41 | int nsel_i[] = MaximumAreaHistogram.nsel(arr);
42 | int maximumArea = Integer.MIN_VALUE;
43 | for(int i = 0; i < arr.length; i++) {
44 | maximumArea = Math.max(maximumArea, (nser_i[i] - nsel_i[i] - 1) * arr[i]);
45 | }
46 | return maximumArea;
47 | }
48 |
49 | public static void main(String[] args) {
50 | int arr[] = new int[]{2, 1, 2};
51 | int ans = maximumAreaHistogram(arr);
52 | System.out.println(ans);
53 | }
54 | }
--------------------------------------------------------------------------------
/src/stack/NGER.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/stack/NGER.class
--------------------------------------------------------------------------------
/src/stack/NGER.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class NGER {
4 |
5 | public static int[] nextGreater(int arr[]) {
6 | Stack stack = new Stack<>();
7 | int ans[] = new int[arr.length];
8 |
9 | for(int i = arr.length - 1; i >= 0; i--) {
10 | while(!stack.isEmpty() && stack.peek() <= arr[i]) {
11 | stack.pop();
12 | }
13 | if(stack.isEmpty()) {
14 | ans[i] = -1;
15 | } else {
16 | ans[i] = stack.peek();
17 | }
18 | stack.push(arr[i]);
19 | }
20 | return ans;
21 | }
22 | public static void main(String[] args) {
23 | int arr[] = {2, 3, 4, 6, 1, 3, 4, 9};
24 | int ans[] = nextGreater(arr);
25 | for(int a : ans) {
26 | System.out.print(a + " ");
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/src/stack/NSER.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/stack/NSER.class
--------------------------------------------------------------------------------
/src/stack/NSER.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class NSER {
4 |
5 | public static int[] nextSmaller(int arr[]) {
6 | Stack stack = new Stack<>();
7 | int ans[] = new int[arr.length];
8 |
9 | for(int i = arr.length - 1; i >= 0; i--) {
10 | while(!stack.isEmpty() && stack.peek() >= arr[i]) {
11 | stack.pop();
12 | }
13 | if(stack.isEmpty()) {
14 | ans[i] = -1;
15 | } else {
16 | ans[i] = stack.peek();
17 | }
18 | stack.push(arr[i]);
19 | }
20 | return ans;
21 | }
22 | public static void main(String[] args) {
23 | int arr[] = {2, 3, 4, 6, 1, 3, 4, 9};
24 | int ans[] = nextSmaller(arr);
25 | for(int a : ans) {
26 | System.out.print(a + " ");
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/src/stack/PostfixEvaluation.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/stack/PostfixEvaluation.class
--------------------------------------------------------------------------------
/src/stack/PostfixEvaluation.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class PostfixEvaluation {
4 |
5 | public static int evaluate(int left, int right, char ch) {
6 | if(ch == '+') return left + right;
7 | else if(ch == '-') return left - right;
8 | else if(ch == '*') return left * right;
9 | else if(ch == '/') return left / right;
10 | else if(ch == '^') return left ^ right;
11 | else return left % right;
12 | }
13 |
14 | public static int evaluatePostfix(String s) {
15 |
16 | Stack stack = new Stack<>();
17 |
18 | for(int i = 0; i < s.length(); i++) {
19 | char ch = s.charAt(i);
20 | if(Character.isDigit(ch)) {
21 | stack.push(Integer.parseInt(String.valueOf(ch)));
22 | } else {
23 | int right = stack.pop();
24 | int left = stack.pop();
25 | stack.push(PostfixEvaluation.evaluate(left, right, ch));
26 | }
27 | }
28 | return stack.pop();
29 | }
30 |
31 | public static void main(String[] args) {
32 | String s = "236*+8-";
33 | int ans = PostfixEvaluation.evaluatePostfix(s);
34 | System.out.println(ans);
35 | }
36 | }
--------------------------------------------------------------------------------
/src/stack/StockSpan.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aakashverma1124/Interview-Preparation-Java/cc127a9919b1ddcc13fca110f49584576377bb20/src/stack/StockSpan.class
--------------------------------------------------------------------------------
/src/stack/StockSpan.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class StockSpan {
4 |
5 | public static int[] stockSpan(int prices[]) {
6 | Stack stack = new Stack<>();
7 | int spans[] = new int[prices.length];
8 | for(int i = 0; i < prices.length; i++) {
9 | while(!stack.isEmpty() && prices[stack.peek()] <= prices[i]) {
10 | stack.pop();
11 | }
12 | if(stack.isEmpty()) {
13 | spans[i] = i - (-1);
14 | } else {
15 | spans[i] = i - stack.peek();
16 | }
17 | stack.push(i);
18 | }
19 | return spans;
20 | }
21 |
22 | public static void main(String[] args) {
23 | int prices[] = new int[]{1, 2, 4, 5, 6};
24 | int spans[] = StockSpan.stockSpan(prices);
25 | for(int span : spans) {
26 | System.out.print(span + " ");
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/src/trie/DesignTrie.java:
--------------------------------------------------------------------------------
1 | class TrieNode {
2 | char character;
3 | TrieNode[] children;
4 | boolean isWordEnding;
5 |
6 | public TrieNode(char character) {
7 | this.character = character;
8 | children = new TrieNode[26];
9 | isWordEnding = false;
10 | }
11 | }
12 |
13 | public class DesignTrie {
14 | TrieNode rootNode;
15 | public DesignTrie() {
16 | this.rootNode = new TrieNode(' ');
17 | }
18 |
19 | public void insert(String word) {
20 | TrieNode tempNode = this.rootNode;
21 | for (int i = 0; i < word.length(); i++) {
22 | int index = word.charAt(i) - 'a';
23 | if (tempNode.children[index] == null) {
24 | tempNode.children[index] = new TrieNode(word.charAt(i));
25 | }
26 | tempNode = tempNode.children[index];
27 | if(i == word.length() - 1) {
28 | tempNode.isWordEnding = true;
29 | }
30 | }
31 | }
32 |
33 | public boolean search(String word) {
34 | TrieNode tempNode = rootNode;
35 | for (int i = 0; i < word.length(); i++) {
36 | int index = word.charAt(i) - 'a';
37 | if (tempNode.children[index] != null) {
38 | tempNode = tempNode.children[index];
39 | if(i == word.length() - 1 && tempNode.isWordEnding) {
40 | return true;
41 | }
42 | } else {
43 | return false;
44 | }
45 | }
46 | return false;
47 | }
48 |
49 | public boolean startsWith(String prefix) {
50 | TrieNode tempNode = rootNode;
51 | for (int i = 0; i < prefix.length(); i++) {
52 | int index = prefix.charAt(i) - 'a';
53 | if (tempNode.children[index] != null) {
54 | tempNode = tempNode.children[index];
55 | } else {
56 | return false;
57 | }
58 | }
59 | return true;
60 | }
61 |
62 | public static void main(String[] args) {
63 | String words[] = new String[]{"abc", "abb", "bca", "bbb"};
64 | DesignTrie trie = new DesignTrie();
65 | for(String word : words) {
66 | trie.insert(word);
67 | }
68 |
69 | String searchWords[] = new String[]{"abc", "abb", "bac", "bbb"};
70 | for(String word : searchWords) {
71 | System.out.print(trie.search(word)+ " ");
72 | }
73 | System.out.println();
74 | String startsWith[] = new String[]{"a", "ba", "bc", "bb"};
75 | for(String word : startsWith) {
76 | System.out.print(trie.startsWith(word) + " ");
77 | }
78 | }
79 |
80 | }
81 |
--------------------------------------------------------------------------------