Skip to content

Commit 293c322

Browse files
author
Prashant Jain
committed
Added Greedy, Graph, SlidingWindow, BFS, Backtracking, DynamicProgramming
1 parent 1eedead commit 293c322

9 files changed

Lines changed: 350 additions & 0 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,4 @@ hs_err_pid*
2525
.idea/
2626
*.iml
2727
build/
28+
out/
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package in.knowledgegate.dsa.backtracking;
2+
3+
import java.util.Scanner;
4+
5+
/**
6+
* The n-queens puzzle is the problem of placing
7+
* n queens on an n x n chessboard such that no
8+
* two queens attack each other.
9+
*
10+
* Given an integer n, return any one solution
11+
* to the n-queens puzzle. You may
12+
* return the answer in any order.
13+
*
14+
* Each solution contains a distinct board
15+
* configuration of the n-queens' placement,
16+
* where 'Q' and '.' both indicate a queen and
17+
* an empty space, respectively.
18+
*
19+
* Example 1:
20+
* Input: n = 4
21+
* Output: [["..Q.","Q...","...Q",".Q.."]]
22+
*
23+
* Example 2:
24+
* Input: n = 1
25+
* Output: [["Q"]]
26+
*
27+
* Constraints:
28+
* 1 <= n <= 30
29+
*/
30+
public class NQueen {
31+
private void printBoard(int[][] board) {
32+
for (int i = 0; i < board.length; i++) {
33+
for (int j = 0; j < board[i].length; j++) {
34+
char out = board[i][j] == 1 ? 'Q' : '.';
35+
System.out.print(" " + out + " ");
36+
}
37+
System.out.println();
38+
}
39+
}
40+
41+
private boolean isMoveSafe(int[][] board,
42+
int row, int col) {
43+
44+
for (int j = 0; j < col; j++) {
45+
if (board[row][j] == 1) {
46+
return false;
47+
}
48+
}
49+
50+
for (int i = row, j = col; i >= 0 && j >=0; i--, j--) {
51+
if (board[i][j] == 1) {
52+
return false;
53+
}
54+
}
55+
56+
for (int i = row, j = col; j >= 0 && i < board.length; j--, i++) {
57+
if (board[i][j] == 1) {
58+
return false;
59+
}
60+
}
61+
62+
return true;
63+
}
64+
65+
/**
66+
* This method is only responsible to put queen
67+
* in a specific column.
68+
*/
69+
private boolean nQueen(int[][] board, int col) {
70+
if (col >= board.length) {
71+
return true;
72+
}
73+
74+
for (int i = 0;i < board.length; i++) {
75+
if (isMoveSafe(board, i, col)) {
76+
board[i][col] = 1;
77+
if (nQueen(board, col + 1)) return true;
78+
board[i][col] = 0;
79+
}
80+
}
81+
82+
return false;
83+
}
84+
85+
private void nQueen(int size) {
86+
int[][] board = new int[size][size];
87+
if (!nQueen(board, 0)) {
88+
System.out.println("Solution does not " +
89+
"exist");
90+
} else {
91+
printBoard(board);
92+
}
93+
}
94+
95+
public static void main(String[] args) {
96+
Scanner scanner = new Scanner(System.in);
97+
NQueen nQueen = new NQueen();
98+
System.out.print("Enter size of board: ");
99+
int size = scanner.nextInt();
100+
nQueen.nQueen(size);
101+
}
102+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package in.knowledgegate.dsa.bfs;
2+
3+
import in.knowledgegate.dsa.binarytree.model.TreeNode;
4+
5+
/**
6+
* Given the root of a binary tree, invert the
7+
* tree, and return its root.
8+
*
9+
* Example 1:
10+
* 4 4
11+
* 2 7 7 2
12+
* 1 3 6 9 9 6 3 1
13+
*
14+
* Input: root = [4,2,7,1,3,6,9]
15+
* Output: [4,7,2,9,6,3,1]
16+
*
17+
* Example 2:
18+
* Input: root = []
19+
* Output: []
20+
*
21+
* Constraints:
22+
* The number of nodes in the tree is in the
23+
* range [0, 100].
24+
* -100 <= Node.val <= 100
25+
*/
26+
public class InvertBinaryTree {
27+
public TreeNode invertTree(TreeNode root) {
28+
if (root == null) return null;
29+
TreeNode temp = root.left;
30+
root.left = root.right;
31+
root.right = temp;
32+
invertTree(root.left);
33+
invertTree(root.right);
34+
return root;
35+
}
36+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package in.knowledgegate.dsa.dynamicprogramming;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
/**
7+
* Given a rod of length n inches and an array
8+
* of prices that includes prices of all pieces of
9+
* size smaller than n. Determine the maximum
10+
* value obtainable by cutting up the rod and
11+
* selling the pieces. For example, if the length
12+
* of the rod is 8 and the values of different pieces
13+
* are given as the following, then the maximum
14+
* obtainable value is 22 (by cutting in two
15+
* pieces of lengths 2 and 6)
16+
*
17+
* Example:
18+
* length | 1 2 3 4 5 6 7 8
19+
* --------------------------------------------
20+
* price | 1 5 8 9 10 17 17 20
21+
* And if the prices are as following, then the
22+
* maximum obtainable value is 24 (by cutting in
23+
* eight pieces of length 1)
24+
*
25+
*/
26+
public class RodCutting {
27+
static int count = 0;
28+
29+
public static void main(String[] args) {
30+
RodCutting rodCutting = new RodCutting();
31+
int price[]
32+
= new int[] { 1, 5, 8, 9, 10, 17, 17,
33+
20, 24 };
34+
int n = price.length;
35+
Map<Integer, Integer> maxProfit =
36+
new HashMap<>();
37+
System.out.println(
38+
"Maximum obtained value is "
39+
+ rodCutting.cutRod(price, n, maxProfit));
40+
System.out.println("count is:" + count);
41+
}
42+
43+
public int cutRod(int prices[], int length,
44+
Map<Integer, Integer> maxProfit) {
45+
if (length <= 0) return 0;
46+
if (maxProfit.containsKey(length)) {
47+
return maxProfit.get(length);
48+
}
49+
count++;
50+
int maxVal = Integer.MIN_VALUE;
51+
52+
for (int i = 0; i < length; i++) {
53+
maxVal = Math.max(maxVal,
54+
prices[i] + cutRod(prices,
55+
length - i - 1, maxProfit));
56+
}
57+
58+
maxProfit.put(length, maxVal);
59+
return maxVal;
60+
}
61+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package in.knowledgegate.dsa.graph;
2+
3+
/**
4+
* In a town, there are n people labeled from
5+
* 1 to n. There is a rumor that one of these
6+
* people is secretly the town judge.
7+
*
8+
* If the town judge exists, then:
9+
*
10+
* The town judge trusts nobody.
11+
* Everybody (except for the town judge) trusts
12+
* the town judge.
13+
* There is exactly one person that satisfies
14+
* properties 1 and 2.
15+
* You are given an array trust where
16+
* trust[i] = [ai, bi] representing that the
17+
* person labeled ai trusts the person labeled bi.
18+
*
19+
* Return the label of the town judge if the town
20+
* judge exists and can be identified, or
21+
* return -1 otherwise.
22+
*
23+
* Example 1:
24+
* Input: n = 2, trust = [[1,2]]
25+
* Output: 2
26+
*
27+
* Example 2:
28+
* Input: n = 3, trust = [[1,3],[2,3]]
29+
* Output: 3
30+
*
31+
* Example 3:
32+
* Input: n = 3, trust = [[1,3],[2,3],[3,1]]
33+
* Output: -1
34+
*
35+
*
36+
* Constraints:
37+
* 1 <= n <= 1000
38+
* 0 <= trust.length <= 104
39+
* trust[i].length == 2
40+
* All the pairs of trust are unique.
41+
* ai != bi
42+
* 1 <= ai, bi <= n
43+
*/
44+
public class FindTheTownJudge {
45+
public int findJudge(int n, int[][] trust) {
46+
int[] count = new int[n + 1];
47+
for (int[] trustRow: trust) {
48+
count[trustRow[0]]--;
49+
count[trustRow[1]]++;
50+
}
51+
52+
for (int i = 1; i < count.length; i++) {
53+
if (count[i] == n-1) {
54+
return i;
55+
}
56+
}
57+
58+
return -1;
59+
}
60+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package in.knowledgegate.dsa.greedy;
2+
3+
/**
4+
* You are given an array prices where prices[i]
5+
* is the price of a given stock on the ith day.
6+
*
7+
* You want to maximize your profit by choosing
8+
* a single day to buy one stock and choosing a
9+
* different day in the future to sell that stock.
10+
*
11+
* Return the maximum profit you can achieve from
12+
* this transaction. If you cannot achieve any
13+
* profit, return 0.
14+
*
15+
* Example 1:
16+
* Input: prices = [7,1,5,3,6,4]
17+
* Output: 5
18+
* Explanation: Buy on day 2 (price = 1) and sell
19+
* on day 5 (price = 6), profit = 6-1 = 5.
20+
* Note that buying on day 2 and selling on day 1
21+
* is not allowed because you must buy before you
22+
* sell.
23+
*
24+
* Example 2:
25+
* Input: prices = [7,6,4,3,1]
26+
* Output: 0
27+
* Explanation: In this case, no transactions
28+
* are done and the max profit = 0.
29+
*
30+
*
31+
* Constraints:
32+
* 1 <= prices.length <= 105
33+
* 0 <= prices[i] <= 104
34+
*/
35+
public class BestTimeToBuyAndSellStock {
36+
public int maxProfit(int[] prices) {
37+
int buy = prices[0], maxProfit = 0;
38+
for (int i = 1; i < prices.length; i++) {
39+
if (buy > prices[i]) {
40+
buy = prices[i];
41+
} else {
42+
int currProfit = prices[i] - buy;
43+
if (currProfit > maxProfit) {
44+
maxProfit = currProfit;
45+
}
46+
}
47+
}
48+
return maxProfit;
49+
}
50+
}
-121 KB
Binary file not shown.
-121 KB
Binary file not shown.
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package in.knowledgegate.dsa.slidingwindow;
2+
3+
import java.util.HashSet;
4+
import java.util.Set;
5+
6+
/**
7+
* Given an integer array nums and an integer k,
8+
* return true if there are two distinct indices
9+
* i and j in the array such that nums[i] == nums[j]
10+
* and abs(i - j) <= k.
11+
*
12+
* Example 1:
13+
* Input: nums = [1,2,3,1], k = 3
14+
* Output: true
15+
*
16+
* Example 2:
17+
* Input: nums = [1,0,1,1], k = 1
18+
* Output: true
19+
*
20+
* Example 3:
21+
* Input: nums = [1,2,3,1,2,3], k = 2
22+
* Output: false
23+
*
24+
* Constraints:
25+
* 1 <= nums.length <= 105
26+
* -109 <= nums[i] <= 109
27+
* 0 <= k <= 105
28+
*/
29+
public class ContainsDuplicate2 {
30+
public boolean containsNearbyDuplicate(int[] nums, int k) {
31+
Set<Integer> window = new HashSet<>();
32+
for (int i = 0; i < nums.length; i++) {
33+
if (i > k) {
34+
window.remove(nums[i - k - 1]);
35+
}
36+
if (!window.add(nums[i])) return true;
37+
}
38+
return false;
39+
}
40+
}

0 commit comments

Comments
 (0)