The post Longest Common Prefix appeared first on [f]izzbuzzer.

]]>`""`

.
```
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
```

```
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
```

```
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
String lcp = strs[0];
for (int i=1; i<strs.length; i++) {
String word = strs[i];
int end = 0;
for (int c=0; c<Math.min(lcp.length(), word.length()); c++) {
if (word.charAt(c) == lcp.charAt(c)) {
end++;
} else {
break;
}
}
lcp = lcp.substring(0, end);
}
return lcp;
}
}
```

The post Longest Common Prefix appeared first on [f]izzbuzzer.

]]>The post Valid Parentheses appeared first on [f]izzbuzzer.

]]>`'('`

, `')'`

, `'{'`

, `'}'`

, `'['`

and `']'`

, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.

```
Example 1:
Input: "([)]"
Output: false
```

```
Example 2:
Input: "{[]}"
Output: true
```

```
Example 3:
Input: "()[]{}"
Output: true
```

```
class Solution {
// Hash table that takes care of the mappings.
private HashMap<Character, Character> mappings;
// Initialize hash map with mappings. This simply makes the code easier to read.
public Solution() {
this.mappings = new HashMap<Character, Character>();
this.mappings.put(')', '(');
this.mappings.put('}', '{');
this.mappings.put(']', '[');
}
public boolean isValid(String s) {
// Initialize a stack to be used in the algorithm.
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// If the current character is a closing bracket.
if (this.mappings.containsKey(c)) {
// Get the top element of the stack. If the stack is empty, set a dummy value of '#'
char topElement = stack.empty() ? '#' : stack.pop();
// If the mapping for this bracket doesn't match the stack's top element, return false.
if (topElement != this.mappings.get(c)) {
return false;
}
} else {
// If it was an opening bracket, push to the stack.
stack.push(c);
}
}
// If the stack still contains elements, then it is an invalid expression.
return stack.isEmpty();
}
}
```

The post Valid Parentheses appeared first on [f]izzbuzzer.

]]>The post Count Directories appeared first on [f]izzbuzzer.

]]>`cd a/b/../c/d/e/../../`

output the visit count of each directory such as: `{a=2, b=1, c=2, d=2, e=1}`

.
```
package problems;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class CountDirectory {
private static Map<String, Integer> count(String path) {
String[] dirs = path.split("/");
Stack<String> stack = new Stack<>();
Map<String, Integer> count = new HashMap<>();
for (String d:dirs) {
String dir = d;
if ("..".equals(dir)) {
stack.pop();
dir = stack.peek();
} else {
stack.add(dir);
if (!count.containsKey(dir)) {
count.put(dir, 0);
}
}
count.put(dir, count.get(dir) + 1);
}
return count;
}
public static void main(String[] args) {
String path = "a/b/../c/d/e/../../";
System.out.println(count(path));
}
}
```

The post Count Directories appeared first on [f]izzbuzzer.

]]>The post Balls and Bins appeared first on [f]izzbuzzer.

]]>`m`

balls and `n`

bin, find out how many ways exist to assign the balls to then bins. `(1,2,3)`

and `(3,2,1)`

are considered the same.
```
Input: m = 3, n = 2
Output: 2
Explanation: (1,2) and (3,0)
```

`m = 3`

, `n = 2`

this means that number of ways `3`

balls can be distributed to `2`

bins is the same as `3`

balls can be distributed to `1`

bin`2`

) bins each of the `n`

bins had a ball and we need to distribute the remaining `m - n`

balls on the `n`

bins```
int assignBalls(int m, int n) {
if (m == 0 || n == 1) {
return 1;
}
if (n > m) {
return assignBalls(m, m);
} else {
return assignBalls(m, n - 1) + assignBalls(m - n, n);
}
}
```

The post Balls and Bins appeared first on [f]izzbuzzer.

]]>The post Shortest Path in Directed Acyclic Graph appeared first on [f]izzbuzzer.

]]>```
package problems;
import java.util.*;
public class DAGShortestPath {
private static class Graph {
private Map<Integer, Set<Integer>> nodes;
private Map<Integer, Map<Integer, Integer>> weights;
public Graph() {
nodes = new HashMap<>();
weights = new HashMap<>();
}
public void addEdge(int u, int v, int weight) {
if (!nodes.containsKey(u)) {
nodes.put(u, new HashSet<>());
}
if (!nodes.containsKey(v)) {
nodes.put(v, new HashSet<>());
}
if (!weights.containsKey(u)) {
weights.put(u, new HashMap<>());
}
nodes.get(u).add(v);
weights.get(u).put(v, weight);
}
public Set<Integer> getNeighbors(int u) {
return nodes.get(u);
}
public int getWeight(int u, int v) {
if (!nodes.containsKey(u)) {
throw new IllegalArgumentException(("Node " + u + " is not in the graph!"));
} else {
if (!weights.get(u).containsKey(v)) {
throw new IllegalArgumentException(("No edge " + u + "->" + v + " exists in the graph!"));
} else {
return weights.get(u).get(v);
}
}
}
public List<Integer> getNodes() {
return new LinkedList<>(nodes.keySet());
}
}
private static Stack<Integer> topologicallySort(Graph g) {
Stack<Integer> ans = new Stack<>();
Stack<Integer> recursionStack = new Stack<>();
Set<Integer> visited = new HashSet<>();
List<Integer> nodes = g.getNodes();
for (int s : nodes) {
if (!visited.contains(s)) {
recursionStack.push(s);
}
while (!recursionStack.isEmpty()) {
int u = recursionStack.peek();
visited.add(u);
int uncompletedNeighborsCount = 0;
for (int v : g.getNeighbors(u)) {
if (!visited.contains(v)) {
recursionStack.push(v);
uncompletedNeighborsCount++;
}
}
if (uncompletedNeighborsCount == 0) {
ans.push(u);
recursionStack.pop();
}
}
}
return ans;
}
private static int shortestPath(Graph g, int s, int t) {
final int INF = 1000;
Stack<Integer> nodes = topologicallySort(g);
int[] dp = new int[nodes.size() + 1];
for (int v = 0; v < dp.length; v++) {
dp[v] = INF;
}
dp[s] = 0;
// Process nodes in topological order
while (!nodes.isEmpty()) {
int u = nodes.pop();
for (int v : g.getNeighbors(u)) {
dp[v] = Math.min(dp[v], dp[u] + g.getWeight(u, v));
}
}
return dp[t];
}
public static void main(String[] args) {
Graph g = new Graph();
g.addEdge(1, 3, 99);
g.addEdge(2, 3, 123);
g.addEdge(2, 4, 88);
g.addEdge(3, 5, 67);
g.addEdge(4, 6, 101);
g.addEdge(5, 6, 123);
g.addEdge(5, 8, 45);
g.addEdge(6, 7, 75);
System.out.println(shortestPath(g, 2, 7));
}
}
```

The post Shortest Path in Directed Acyclic Graph appeared first on [f]izzbuzzer.

]]>The post Coin in Line appeared first on [f]izzbuzzer.

]]>```
public class CoinInLine {
public static boolean solve(int n, int x, int y) {
boolean[] dp = new boolean[n+1];
dp[0] = false;
dp[1] = true;
for (int i=2; i<=n; i++) {
if (i-1>=0 && dp[i-1] == false) {
dp[i] = true;
} else if (i-x>=0 && dp[i-x] == false) {
dp[i] = true;
} else if (i-y>=0 && dp[i-y] == false) {
dp[i] = true;
} else {
dp[i] = false;
}
}
return dp[n];
}
public static void main(String[] args) {
System.out.println(solve(5, 3, 4));
}
}
```

The post Coin in Line appeared first on [f]izzbuzzer.

]]>The post Replace And Remove appeared first on [f]izzbuzzer.

]]>- Replace each ‘a’ with ‘dd’
- Delete each ‘b’

```
package problems;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Remove 'b's and replace 'a's with 'dd'
*/
public class ReplaceAndRemove {
private static final Set<Character> ALPHABET = new HashSet<Character>(Arrays.asList('a', 'b', 'c', 'd'));
private static int endIndex(char[] s) {
for (int i = 0; i < s.length; i++) {
if (!ALPHABET.contains(s[i])) {
return i - 1;
}
}
return s.length - 1;
}
private static char[] solve(char[] s) {
int countA = 0;
int writeIndex = 0;
for (int i = 0; i < s.length; i++) {
if (s[i] == 'a') {
countA++;
}
if (s[i] != 'b') {
s[writeIndex++] = s[i];
}
}
int newLen = ((endIndex(s) + 1) - countA) + 2 * countA;
writeIndex = newLen - 1;
int readIndex = endIndex(s);
while (readIndex >= 0) {
if (s[readIndex] == 'a') {
s[writeIndex--] = 'd';
s[writeIndex--] = 'd';
} else {
s[writeIndex--] = s[readIndex];
}
readIndex--;
}
// Clean any remaining chars
for (int i = newLen; i < s.length; i++) {
s[i] = Character.MIN_VALUE;
}
return s;
}
public static void main(String[] args) {
char[] s = Arrays.copyOf("bca".toCharArray(), 16);
System.out.println(new String(solve(s)));
}
}
```

The post Replace And Remove appeared first on [f]izzbuzzer.

]]>The post Out of Boundary Paths appeared first on [f]izzbuzzer.

]]>- Once you move the ball out of boundary, you cannot move it back.
- The length and height of the grid is in range [1,50].
- N is in range [0,50].

Input: m = 1, n = 3, N = 3, i = 0, j = 1 Output: 12

Input: m = 2, n = 2, N = 2, i = 0, j = 0 Output: 6

```
class Solution {
final int MOD = 1000000007;
public int findPaths(int m, int n, int N, int i, int j) {
// dp[k][i][j] = number of paths with at most k steps starting from position (i,j)
int[][][] dp = new int[N+1][m][n];
for (int k=1; k<=N; k++){
for (int r=0; r<m; r++) {
for (int c=0; c<n; c++) {
if (r>0) {
dp[k][r][c] += dp[k-1][r-1][c];
} else {
dp[k][r][c] += 1;
}
dp[k][r][c] %= MOD;
if (r==m-1) {
dp[k][r][c] += 1;
} else {
dp[k][r][c] += dp[k-1][r+1][c];
}
dp[k][r][c] %= MOD;
if (c>0) {
dp[k][r][c] += dp[k-1][r][c-1];
} else {
dp[k][r][c] += 1;
}
dp[k][r][c] %= MOD;
if (c==n-1) {
dp[k][r][c] += 1;
} else {
dp[k][r][c] += dp[k-1][r][c+1];
}
dp[k][r][c] %= MOD;
}
}
}
return dp[N][i][j];
}
}
```

The post Out of Boundary Paths appeared first on [f]izzbuzzer.

]]>The post Unique Paths II appeared first on [f]izzbuzzer.

]]>A robot is located at the top-left corner of a

`m x n`

grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
Note: `m`

and `n`

will be at most 100.
Input: [ [0,0,0], [0,1,0], [0,0,0] ] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right

```
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
final int OBSTACLE = 1;
int n = obstacleGrid.length;
int m = obstacleGrid[0].length;
int[][] dp = new int[n][m];
if (obstacleGrid[0][0] == OBSTACLE) {
dp[0][0] = 0;
} else {
dp[0][0] = 1;
}
for (int i=1; i<n; i++) {
if (obstacleGrid[i][0] == OBSTACLE) {
dp[i][0] = 0;
} else {
dp[i][0] = Math.min(dp[i-1][0], 1);
}
}
for (int j=1; j<m; j++) {
if (obstacleGrid[0][j] == OBSTACLE) {
dp[0][j] = 0;
} else {
dp[0][j] = Math.min(dp[0][j-1], 1);
}
}
for (int i=1; i<n; i++) {
for (int j=1; j<m; j++) {
if (obstacleGrid[i][j] == OBSTACLE) {
dp[i][j] = 0;
} else {
if (dp[i-1][j] > 0 && dp[i][j-1] > 0) {
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}else if (dp[i-1][j] > 0) {
dp[i][j] = dp[i-1][j];
} else if (dp[i][j-1] > 0) {
dp[i][j] = dp[i][j-1];
} else {
dp[i][j] = 0;
}
}
}
}
return dp[n-1][m-1];
}
}
```

The post Unique Paths II appeared first on [f]izzbuzzer.

]]>The post Minimum Swaps To Make Sequences Increasing appeared first on [f]izzbuzzer.

]]>We have two integer sequences

`A`

and `B`

of the same non-zero length.
We are allowed to swap elements `A[i]`

and `B[i]`

. Note that both elements are in the same index position in their respective sequences.

At the end of some number of swaps, A and B are both strictly increasing. (A sequence is strictly increasing if and only if `A[0] < A[1] < A[2] < ... < A[A.length - 1]`

.)

Given `A`

and `B`

, return the minimum number of swaps to make both sequences strictly increasing. It is guaranteed that the given input always makes it possible.

**Example**

Input: A = [1,3,5,4], B = [1,2,3,7] Output: 1 Explanation: Swap A[3] and B[3]. Then the sequences are: A = [1, 3, 5, 7] and B = [1, 2, 3, 4] which are both strictly increasing.

**Note**

`A`

, `B`

are arrays with the same length, and that length will be in the range `[1, 1000]`

.

`A[i]`

, `B[i]`

are integer values in the range `[0, 2000]`

.

**Solution**

We use dynamic programming. The cost of making both sequences increasing up to the first `i`

columns can be expressed in terms of the cost of making both sequences increasing up to the first `i-1`

columns. This is because the only thing that matters to the `i`

th column is whether the previous column was swapped or not. This makes dynamic programming an ideal choice.

Let’s remember `n1`

(natural1), the cost of making the first `i-1`

columns increasing and not swapping the i-1th column; and `s1`

(swapped1), the cost of making the first i-1 columns increasing and swapping the i-1th column.

Now we want candidates `n2`

(and `s2`

), the costs of making the first i columns increasing if we do not swap (or swap, respectively) the ith column.

For convenience, say `a1 = A[i-1]`

, `b1 = B[i-1]`

and `a2 = A[i]`

, `b2 = B[i]`

.

Now, if a1 < a2 and b1 < b2, then it is allowed to have both of these columns natural (unswapped), or both of these columns swapped. This possibility leads to n2 = min(n2, n1) and s2 = min(s2, s1 + 1).

Another, (not exclusive) possibility is that a1 < b2 and b1 < a2. This means that it is allowed to have exactly one of these columns swapped. This possibility leads to n2 = min(n2, s1) or s2 = min(s2, n1 + 1). This can be the case if `A = [1, 6]`

and `B = [3, 3]`

.

Note that it is important to use two if statements separately, because both of the above possibilities might be possible.

At the end, the optimal solution must leave the last column either natural or swapped, so we take the minimum number of swaps between the two possibilities.

**Code**

class Solution { public int minSwap(int[] A, int[] B) { // n: natural, s: swapped int n1 = 0, s1 = 1; for (int i = 1; i < A.length; ++i) { int n2 = Integer.MAX_VALUE, s2 = Integer.MAX_VALUE; if (A[i-1] < A[i] && B[i-1] < B[i]) { n2 = Math.min(n2, n1); s2 = Math.min(s2, s1 + 1); } if (A[i-1] < B[i] && B[i-1] < A[i]) { n2 = Math.min(n2, s1); s2 = Math.min(s2, n1 + 1); } n1 = n2; s1 = s2; } return Math.min(n1, s1); } }

The post Minimum Swaps To Make Sequences Increasing appeared first on [f]izzbuzzer.

]]>